blob: 7dc2c3579a3fe04ea13576612bffcf83ed1c7787 [file] [log] [blame]
Jonathan Hart501f7882018-07-24 14:39:57 -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.kafka.impl;
17
18import com.fasterxml.jackson.databind.JsonNode;
Carmelo Cascone7e73fa12019-07-15 18:29:01 -070019import org.osgi.service.component.annotations.Activate;
20import org.osgi.service.component.annotations.Component;
21import org.osgi.service.component.annotations.Deactivate;
22import org.osgi.service.component.annotations.Reference;
23import org.osgi.service.component.annotations.ReferenceCardinality;
Jonathan Hart501f7882018-07-24 14:39:57 -070024import org.apache.kafka.clients.producer.KafkaProducer;
25import org.apache.kafka.clients.producer.ProducerRecord;
26import org.apache.kafka.common.serialization.StringSerializer;
Jonathan Harta11792a2018-08-19 13:48:17 -070027import org.onosproject.cluster.ClusterService;
Jonathan Hart501f7882018-07-24 14:39:57 -070028import org.onosproject.core.ApplicationId;
29import org.onosproject.core.CoreService;
30import org.onosproject.net.config.ConfigFactory;
31import org.onosproject.net.config.NetworkConfigEvent;
32import org.onosproject.net.config.NetworkConfigListener;
33import org.onosproject.net.config.NetworkConfigRegistry;
34import org.onosproject.net.config.basics.SubjectFactories;
35import org.opencord.kafka.EventBusService;
36import org.slf4j.Logger;
37
38import java.util.Properties;
39import java.util.concurrent.ExecutorService;
Jonathan Harta11792a2018-08-19 13:48:17 -070040import java.util.concurrent.TimeUnit;
Jonathan Hart501f7882018-07-24 14:39:57 -070041
42import static com.google.common.base.Preconditions.checkNotNull;
43import static java.util.concurrent.Executors.newSingleThreadExecutor;
44import static org.onlab.util.Tools.groupedThreads;
45import static org.slf4j.LoggerFactory.getLogger;
46
47/**
48 * Sends events to a Kafka event bus.
49 */
Jonathan Hart501f7882018-07-24 14:39:57 -070050@Component(immediate = true)
51public class KafkaIntegration implements EventBusService {
52
53 private final Logger log = getLogger(getClass());
54 private static final Class<KafkaConfig>
55 KAFKA_CONFIG_CLASS = KafkaConfig.class;
56
57 private static final String APP_NAME = "org.opencord.kafka";
58 private ApplicationId appId;
59
Matteo Scandolo246f7232019-05-09 15:57:39 -070060 private Boolean kafkaStarted = false;
61
Carmelo Cascone7e73fa12019-07-15 18:29:01 -070062 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonathan Hart501f7882018-07-24 14:39:57 -070063 protected CoreService coreService;
64
Carmelo Cascone7e73fa12019-07-15 18:29:01 -070065 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonathan Harta11792a2018-08-19 13:48:17 -070066 protected ClusterService clusterService;
67
Carmelo Cascone7e73fa12019-07-15 18:29:01 -070068 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonathan Hart501f7882018-07-24 14:39:57 -070069 protected NetworkConfigRegistry configRegistry;
70
71 private static StringSerializer stringSerializer = new StringSerializer();
72
73 private KafkaProducer<String, String> kafkaProducer;
74
75 private InternalNetworkConfigListener configListener =
76 new InternalNetworkConfigListener();
77
78 private final ExecutorService executor = newSingleThreadExecutor(
79 groupedThreads(this.getClass().getSimpleName(), "events", log));
80
81 private ConfigFactory<ApplicationId, KafkaConfig> kafkaConfigFactory =
82 new ConfigFactory<ApplicationId, KafkaConfig>(
83 SubjectFactories.APP_SUBJECT_FACTORY, KAFKA_CONFIG_CLASS,
84 "kafka") {
85 @Override
86 public KafkaConfig createConfig() {
87 return new KafkaConfig();
88 }
89 };
90
Jonathan Harta11792a2018-08-19 13:48:17 -070091 private static final String CLIENT_ID = "client.id";
Jonathan Hart501f7882018-07-24 14:39:57 -070092 private static final String BOOTSTRAP_SERVERS = "bootstrap.servers";
93 private static final String RETRIES = "retries";
94 private static final String RECONNECT_BACKOFF = "reconnect.backoff.ms";
95 private static final String INFLIGHT_REQUESTS =
96 "max.in.flight.requests.per.connection";
97 private static final String ACKS = "acks";
98 private static final String KEY_SERIALIZER = "key.serializer";
99 private static final String VALUE_SERIALIZER = "value.serializer";
100 private static final String STRING_SERIALIZER =
101 stringSerializer.getClass().getCanonicalName();
102
103 private static final String TIMESTAMP = "timestamp";
104
105 @Activate
106 public void activate() {
107 appId = coreService.registerApplication(APP_NAME);
108 configRegistry.registerConfigFactory(kafkaConfigFactory);
109 configRegistry.addListener(configListener);
Andy Bavier8e9eeef2018-09-19 15:40:58 -0700110 configure();
Jonathan Hart501f7882018-07-24 14:39:57 -0700111
Jonathan Hart501f7882018-07-24 14:39:57 -0700112 log.info("Started");
113 }
114
115 @Deactivate
116 public void deactivate() {
117 configRegistry.removeListener(configListener);
118 configRegistry.unregisterConfigFactory(kafkaConfigFactory);
119
120 executor.shutdownNow();
121
122 shutdownKafka();
123 log.info("Stopped");
124 }
125
126 private void configure() {
127 KafkaConfig config =
128 configRegistry.getConfig(appId, KAFKA_CONFIG_CLASS);
129 if (config == null) {
130 log.info("Kafka configuration not present");
131 return;
132 }
133 configure(config);
134 }
135
136 private void configure(KafkaConfig config) {
137 checkNotNull(config);
138
139 Properties properties = new Properties();
Jonathan Harta11792a2018-08-19 13:48:17 -0700140 properties.put(CLIENT_ID, clusterService.getLocalNode().id().toString());
Jonathan Hart501f7882018-07-24 14:39:57 -0700141 properties.put(BOOTSTRAP_SERVERS, config.getBootstrapServers());
142 properties.put(RETRIES, config.getRetries());
143 properties.put(RECONNECT_BACKOFF, config.getReconnectBackoff());
144 properties.put(INFLIGHT_REQUESTS, config.getInflightRequests());
145 properties.put(ACKS, config.getAcks());
146 properties.put(KEY_SERIALIZER, STRING_SERIALIZER);
147 properties.put(VALUE_SERIALIZER, STRING_SERIALIZER);
148
149 startKafka(properties);
150 }
151
152 private void unconfigure() {
153 shutdownKafka();
154 }
155
156 private void startKafka(Properties properties) {
Matteo Scandolo246f7232019-05-09 15:57:39 -0700157 if (!kafkaStarted) {
158 // Kafka client doesn't play nice with the default OSGi classloader
159 // This workaround temporarily changes the thread's classloader so that
160 // the Kafka client can load the serializer classes.
161 ClassLoader original = Thread.currentThread().getContextClassLoader();
162 Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
163 try {
164 log.info("Starting Kafka producer");
165 kafkaProducer = new KafkaProducer<>(properties);
166 kafkaStarted = true;
167 } finally {
168 Thread.currentThread().setContextClassLoader(original);
169 }
Jonathan Hart501f7882018-07-24 14:39:57 -0700170 }
171 }
172
173 private void shutdownKafka() {
174 if (kafkaProducer != null) {
Jonathan Harta11792a2018-08-19 13:48:17 -0700175 log.info("Shutting down Kafka producer");
176 kafkaProducer.flush();
177 kafkaProducer.close(0, TimeUnit.MILLISECONDS);
Jonathan Hart501f7882018-07-24 14:39:57 -0700178 kafkaProducer = null;
179 }
Matteo Scandolo246f7232019-05-09 15:57:39 -0700180 kafkaStarted = false;
Jonathan Hart501f7882018-07-24 14:39:57 -0700181 }
182
183 private void logException(Exception e) {
184 if (e != null) {
185 log.error("Exception while sending to Kafka", e);
186 }
187 }
188
189 @Override
190 public void send(String topic, JsonNode data) {
191 if (kafkaProducer == null) {
Matteo Scandoloe53b12a2018-09-13 10:06:58 -0700192 log.warn("Not sending event as kafkaProducer is not defined: {}", data.toString());
Jonathan Hart501f7882018-07-24 14:39:57 -0700193 return;
194 }
195
196 if (log.isTraceEnabled()) {
197 log.trace("Sending event to Kafka: {}", data.toString());
198 }
199
200 kafkaProducer.send(new ProducerRecord<>(topic, data.toString()),
201 (r, e) -> logException(e));
202 }
203
204 private class InternalNetworkConfigListener implements NetworkConfigListener {
205
206 @Override
207 public void event(NetworkConfigEvent event) {
Jonathan Harta11792a2018-08-19 13:48:17 -0700208 log.info("Event type {}", event.type());
Jonathan Hart501f7882018-07-24 14:39:57 -0700209 switch (event.type()) {
210 case CONFIG_ADDED:
211 case CONFIG_UPDATED:
Matteo Scandolo246f7232019-05-09 15:57:39 -0700212 unconfigure();
Jonathan Hart501f7882018-07-24 14:39:57 -0700213 configure((KafkaConfig) event.config().get());
214 break;
215 case CONFIG_REMOVED:
216 unconfigure();
217 break;
218 case CONFIG_REGISTERED:
219 case CONFIG_UNREGISTERED:
220 default:
221 break;
222 }
223 }
224
225 @Override
226 public boolean isRelevant(NetworkConfigEvent event) {
227 return event.configClass().equals(KAFKA_CONFIG_CLASS);
228 }
229 }
230}