blob: 7ecbaf6b474dda3e9528d7b249a3d152cebbb0ad [file] [log] [blame]
Jonathan Hart1d34c8b2018-05-05 15:37:28 -07001/*
2 * Copyright 2018-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.opencord.olt.kafka;
17
18import com.fasterxml.jackson.databind.ObjectMapper;
19import com.fasterxml.jackson.databind.node.ObjectNode;
20import org.apache.felix.scr.annotations.Activate;
21import org.apache.felix.scr.annotations.Component;
22import org.apache.felix.scr.annotations.Deactivate;
23import org.apache.felix.scr.annotations.Reference;
24import org.apache.felix.scr.annotations.ReferenceCardinality;
25import org.apache.kafka.clients.producer.KafkaProducer;
26import org.apache.kafka.clients.producer.ProducerRecord;
27import org.apache.kafka.common.serialization.StringSerializer;
28import org.onosproject.core.ApplicationId;
29import org.onosproject.core.CoreService;
30import org.onosproject.net.AnnotationKeys;
31import org.onosproject.net.Port;
32import org.onosproject.net.config.ConfigFactory;
33import org.onosproject.net.config.NetworkConfigEvent;
34import org.onosproject.net.config.NetworkConfigListener;
35import org.onosproject.net.config.NetworkConfigRegistry;
36import org.onosproject.net.config.basics.SubjectFactories;
37import org.opencord.olt.AccessDeviceEvent;
38import org.opencord.olt.AccessDeviceListener;
39import org.opencord.olt.AccessDeviceService;
40import org.slf4j.Logger;
41
Jonathan Hart6960f822018-07-02 15:19:14 -070042import java.time.Instant;
Jonathan Hart1d34c8b2018-05-05 15:37:28 -070043import java.util.Properties;
44import java.util.concurrent.ExecutorService;
45
46import static com.google.common.base.Preconditions.checkNotNull;
47import static java.util.concurrent.Executors.newSingleThreadExecutor;
48import static org.onlab.util.Tools.groupedThreads;
49import static org.slf4j.LoggerFactory.getLogger;
50
51/**
52 * Sends access device events to an external system.
53 */
54@Component(immediate = true)
55public class KafkaIntegration {
56
57 private final Logger log = getLogger(getClass());
58 private static final Class<OltKafkaConfig>
59 OLT_KAFKA_CONFIG_CLASS = OltKafkaConfig.class;
60
61 private static final String APP_NAME = "org.opencord.olt";
62 private ApplicationId appId;
63
64 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
65 protected CoreService coreService;
66
67 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
68 protected NetworkConfigRegistry configRegistry;
69
70 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
71 protected AccessDeviceService accessDeviceService;
72
73 private static StringSerializer stringSerializer = new StringSerializer();
74
75 private KafkaProducer<String, String> kafkaProducer;
76
77 private InternalNetworkConfigListener configListener =
78 new InternalNetworkConfigListener();
79 private InternalAccessDeviceListener listener =
80 new InternalAccessDeviceListener();
81
82 private final ExecutorService executor = newSingleThreadExecutor(
83 groupedThreads(this.getClass().getSimpleName(), "events", log));
84
85 private ConfigFactory<ApplicationId, OltKafkaConfig> kafkaConfigFactory =
86 new ConfigFactory<ApplicationId, OltKafkaConfig>(
87 SubjectFactories.APP_SUBJECT_FACTORY, OLT_KAFKA_CONFIG_CLASS,
88 "kafka") {
89 @Override
90 public OltKafkaConfig createConfig() {
91 return new OltKafkaConfig();
92 }
93 };
94
95 private static final String BOOTSTRAP_SERVERS = "bootstrap.servers";
96 private static final String RETRIES = "retries";
97 private static final String RECONNECT_BACKOFF = "reconnect.backoff.ms";
98 private static final String INFLIGHT_REQUESTS =
99 "max.in.flight.requests.per.connection";
100 private static final String ACKS = "acks";
101 private static final String KEY_SERIALIZER = "key.serializer";
102 private static final String VALUE_SERIALIZER = "value.serializer";
103 private static final String STRING_SERIALIZER =
104 stringSerializer.getClass().getCanonicalName();
105
106 private static final String ONU_TOPIC = "onu.events";
107
108 private static final String STATUS = "status";
109 private static final String SERIAL_NUMBER = "serial_number";
110 private static final String UNI_PORT_ID = "uni_port_id";
111 private static final String OF_DPID = "of_dpid";
112 private static final String ACTIVATED = "activated";
Jonathan Hart6960f822018-07-02 15:19:14 -0700113 private static final String TIMESTAMP = "timestamp";
Jonathan Hart1d34c8b2018-05-05 15:37:28 -0700114
115 @Activate
116 public void activate() {
117 appId = coreService.registerApplication(APP_NAME);
118 configRegistry.registerConfigFactory(kafkaConfigFactory);
119 configRegistry.addListener(configListener);
120 accessDeviceService.addListener(listener);
121
122 configure();
123
124 log.info("Started");
125 }
126
127 @Deactivate
128 public void deactivate() {
129 accessDeviceService.removeListener(listener);
130 configRegistry.removeListener(configListener);
131 configRegistry.unregisterConfigFactory(kafkaConfigFactory);
132
133 executor.shutdownNow();
134
135 shutdownKafka();
136 log.info("Stopped");
137 }
138
139 private void configure() {
140 OltKafkaConfig config =
141 configRegistry.getConfig(appId, OLT_KAFKA_CONFIG_CLASS);
142 if (config == null) {
143 log.info("OLT Kafka config not found");
144 return;
145 }
146 configure(config);
147 }
148
149 private void configure(OltKafkaConfig config) {
150 checkNotNull(config);
151
152 Properties properties = new Properties();
153 properties.put(BOOTSTRAP_SERVERS, config.getBootstrapServers());
154 properties.put(RETRIES, config.getRetries());
155 properties.put(RECONNECT_BACKOFF, config.getReconnectBackoff());
156 properties.put(INFLIGHT_REQUESTS, config.getInflightRequests());
157 properties.put(ACKS, config.getAcks());
158 properties.put(KEY_SERIALIZER, STRING_SERIALIZER);
159 properties.put(VALUE_SERIALIZER, STRING_SERIALIZER);
160
161 startKafka(properties);
162 }
163
164 private void unconfigure() {
165 shutdownKafka();
166 }
167
168 private void startKafka(Properties properties) {
169 shutdownKafka();
170
171 // Kafka client doesn't play nice with the default OSGi classloader
172 // This workaround temporarily changes the thread's classloader so that
173 // the Kafka client can load the serializer classes.
174 ClassLoader original = Thread.currentThread().getContextClassLoader();
175 Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
176 try {
177 kafkaProducer = new KafkaProducer<>(properties);
178 } finally {
179 Thread.currentThread().setContextClassLoader(original);
180 }
181 }
182
183 private void shutdownKafka() {
184 if (kafkaProducer != null) {
185 kafkaProducer.close();
186 kafkaProducer = null;
187 }
188 }
189
190 private void sendUniAddEvent(AccessDeviceEvent event) {
191 if (kafkaProducer == null) {
192 return;
193 }
194
195 Port port = event.port().get();
196 String serialNumber = port.annotations().value(AnnotationKeys.PORT_NAME);
197
198 ObjectMapper mapper = new ObjectMapper();
Jonathan Hart1d34c8b2018-05-05 15:37:28 -0700199 ObjectNode onuNode = mapper.createObjectNode();
Jonathan Hart6960f822018-07-02 15:19:14 -0700200 onuNode.put(TIMESTAMP, Instant.now().toString());
Jonathan Hart1d34c8b2018-05-05 15:37:28 -0700201 onuNode.put(STATUS, ACTIVATED);
202 onuNode.put(SERIAL_NUMBER, serialNumber);
203 onuNode.put(UNI_PORT_ID, port.number().toLong());
204 onuNode.put(OF_DPID, port.element().id().toString());
205
206 if (log.isDebugEnabled()) {
207 log.debug("Sending UNI ADD event: {}", onuNode.toString());
208 }
209
210 kafkaProducer.send(new ProducerRecord<>(ONU_TOPIC, onuNode.toString()),
211 (r, e) -> logException(e));
212 }
213
214 private void logException(Exception e) {
215 if (e != null) {
216 log.error("Exception while sending to Kafka", e);
217 }
218 }
219
220 private class InternalNetworkConfigListener implements NetworkConfigListener {
221
222 @Override
223 public void event(NetworkConfigEvent event) {
224 switch (event.type()) {
225 case CONFIG_ADDED:
226 case CONFIG_UPDATED:
227 configure((OltKafkaConfig) event.config().get());
228 break;
229 case CONFIG_REMOVED:
230 unconfigure();
231 break;
232 case CONFIG_REGISTERED:
233 case CONFIG_UNREGISTERED:
234 default:
235 break;
236 }
237 }
238
239 @Override
240 public boolean isRelevant(NetworkConfigEvent event) {
241 return event.configClass().equals(OLT_KAFKA_CONFIG_CLASS);
242 }
243 }
244
245 private class InternalAccessDeviceListener implements AccessDeviceListener {
246
247 @Override
248 public void event(AccessDeviceEvent accessDeviceEvent) {
Jonathan Hart6960f822018-07-02 15:19:14 -0700249 log.debug("KafkaIntegration got {} event for {}/{}",
250 accessDeviceEvent.type(), accessDeviceEvent.subject(), accessDeviceEvent.port());
Jonathan Hart1d34c8b2018-05-05 15:37:28 -0700251 switch (accessDeviceEvent.type()) {
252 case UNI_ADDED:
253 executor.execute(() ->
254 KafkaIntegration.this.sendUniAddEvent(accessDeviceEvent));
255 break;
256 case UNI_REMOVED:
257 default:
258 break;
259 }
260 }
261 }
262}