blob: 60be6e64ff0d93cae2f6ec7a56836295beea56de [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
42import java.util.Properties;
43import java.util.concurrent.ExecutorService;
44
45import static com.google.common.base.Preconditions.checkNotNull;
46import static java.util.concurrent.Executors.newSingleThreadExecutor;
47import static org.onlab.util.Tools.groupedThreads;
48import static org.slf4j.LoggerFactory.getLogger;
49
50/**
51 * Sends access device events to an external system.
52 */
53@Component(immediate = true)
54public class KafkaIntegration {
55
56 private final Logger log = getLogger(getClass());
57 private static final Class<OltKafkaConfig>
58 OLT_KAFKA_CONFIG_CLASS = OltKafkaConfig.class;
59
60 private static final String APP_NAME = "org.opencord.olt";
61 private ApplicationId appId;
62
63 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
64 protected CoreService coreService;
65
66 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
67 protected NetworkConfigRegistry configRegistry;
68
69 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
70 protected AccessDeviceService accessDeviceService;
71
72 private static StringSerializer stringSerializer = new StringSerializer();
73
74 private KafkaProducer<String, String> kafkaProducer;
75
76 private InternalNetworkConfigListener configListener =
77 new InternalNetworkConfigListener();
78 private InternalAccessDeviceListener listener =
79 new InternalAccessDeviceListener();
80
81 private final ExecutorService executor = newSingleThreadExecutor(
82 groupedThreads(this.getClass().getSimpleName(), "events", log));
83
84 private ConfigFactory<ApplicationId, OltKafkaConfig> kafkaConfigFactory =
85 new ConfigFactory<ApplicationId, OltKafkaConfig>(
86 SubjectFactories.APP_SUBJECT_FACTORY, OLT_KAFKA_CONFIG_CLASS,
87 "kafka") {
88 @Override
89 public OltKafkaConfig createConfig() {
90 return new OltKafkaConfig();
91 }
92 };
93
94 private static final String BOOTSTRAP_SERVERS = "bootstrap.servers";
95 private static final String RETRIES = "retries";
96 private static final String RECONNECT_BACKOFF = "reconnect.backoff.ms";
97 private static final String INFLIGHT_REQUESTS =
98 "max.in.flight.requests.per.connection";
99 private static final String ACKS = "acks";
100 private static final String KEY_SERIALIZER = "key.serializer";
101 private static final String VALUE_SERIALIZER = "value.serializer";
102 private static final String STRING_SERIALIZER =
103 stringSerializer.getClass().getCanonicalName();
104
105 private static final String ONU_TOPIC = "onu.events";
106
107 private static final String STATUS = "status";
108 private static final String SERIAL_NUMBER = "serial_number";
109 private static final String UNI_PORT_ID = "uni_port_id";
110 private static final String OF_DPID = "of_dpid";
111 private static final String ACTIVATED = "activated";
112
113 @Activate
114 public void activate() {
115 appId = coreService.registerApplication(APP_NAME);
116 configRegistry.registerConfigFactory(kafkaConfigFactory);
117 configRegistry.addListener(configListener);
118 accessDeviceService.addListener(listener);
119
120 configure();
121
122 log.info("Started");
123 }
124
125 @Deactivate
126 public void deactivate() {
127 accessDeviceService.removeListener(listener);
128 configRegistry.removeListener(configListener);
129 configRegistry.unregisterConfigFactory(kafkaConfigFactory);
130
131 executor.shutdownNow();
132
133 shutdownKafka();
134 log.info("Stopped");
135 }
136
137 private void configure() {
138 OltKafkaConfig config =
139 configRegistry.getConfig(appId, OLT_KAFKA_CONFIG_CLASS);
140 if (config == null) {
141 log.info("OLT Kafka config not found");
142 return;
143 }
144 configure(config);
145 }
146
147 private void configure(OltKafkaConfig config) {
148 checkNotNull(config);
149
150 Properties properties = new Properties();
151 properties.put(BOOTSTRAP_SERVERS, config.getBootstrapServers());
152 properties.put(RETRIES, config.getRetries());
153 properties.put(RECONNECT_BACKOFF, config.getReconnectBackoff());
154 properties.put(INFLIGHT_REQUESTS, config.getInflightRequests());
155 properties.put(ACKS, config.getAcks());
156 properties.put(KEY_SERIALIZER, STRING_SERIALIZER);
157 properties.put(VALUE_SERIALIZER, STRING_SERIALIZER);
158
159 startKafka(properties);
160 }
161
162 private void unconfigure() {
163 shutdownKafka();
164 }
165
166 private void startKafka(Properties properties) {
167 shutdownKafka();
168
169 // Kafka client doesn't play nice with the default OSGi classloader
170 // This workaround temporarily changes the thread's classloader so that
171 // the Kafka client can load the serializer classes.
172 ClassLoader original = Thread.currentThread().getContextClassLoader();
173 Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
174 try {
175 kafkaProducer = new KafkaProducer<>(properties);
176 } finally {
177 Thread.currentThread().setContextClassLoader(original);
178 }
179 }
180
181 private void shutdownKafka() {
182 if (kafkaProducer != null) {
183 kafkaProducer.close();
184 kafkaProducer = null;
185 }
186 }
187
188 private void sendUniAddEvent(AccessDeviceEvent event) {
189 if (kafkaProducer == null) {
190 return;
191 }
192
193 Port port = event.port().get();
194 String serialNumber = port.annotations().value(AnnotationKeys.PORT_NAME);
195
196 ObjectMapper mapper = new ObjectMapper();
197
198 ObjectNode onuNode = mapper.createObjectNode();
199 onuNode.put(STATUS, ACTIVATED);
200 onuNode.put(SERIAL_NUMBER, serialNumber);
201 onuNode.put(UNI_PORT_ID, port.number().toLong());
202 onuNode.put(OF_DPID, port.element().id().toString());
203
204 if (log.isDebugEnabled()) {
205 log.debug("Sending UNI ADD event: {}", onuNode.toString());
206 }
207
208 kafkaProducer.send(new ProducerRecord<>(ONU_TOPIC, onuNode.toString()),
209 (r, e) -> logException(e));
210 }
211
212 private void logException(Exception e) {
213 if (e != null) {
214 log.error("Exception while sending to Kafka", e);
215 }
216 }
217
218 private class InternalNetworkConfigListener implements NetworkConfigListener {
219
220 @Override
221 public void event(NetworkConfigEvent event) {
222 switch (event.type()) {
223 case CONFIG_ADDED:
224 case CONFIG_UPDATED:
225 configure((OltKafkaConfig) event.config().get());
226 break;
227 case CONFIG_REMOVED:
228 unconfigure();
229 break;
230 case CONFIG_REGISTERED:
231 case CONFIG_UNREGISTERED:
232 default:
233 break;
234 }
235 }
236
237 @Override
238 public boolean isRelevant(NetworkConfigEvent event) {
239 return event.configClass().equals(OLT_KAFKA_CONFIG_CLASS);
240 }
241 }
242
243 private class InternalAccessDeviceListener implements AccessDeviceListener {
244
245 @Override
246 public void event(AccessDeviceEvent accessDeviceEvent) {
247 switch (accessDeviceEvent.type()) {
248 case UNI_ADDED:
249 executor.execute(() ->
250 KafkaIntegration.this.sendUniAddEvent(accessDeviceEvent));
251 break;
252 case UNI_REMOVED:
253 default:
254 break;
255 }
256 }
257 }
258}