blob: 0720a868a3a61f9048bbf14fd390864a2d3abefb [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;
19import org.apache.felix.scr.annotations.Activate;
20import org.apache.felix.scr.annotations.Component;
21import org.apache.felix.scr.annotations.Deactivate;
22import org.apache.felix.scr.annotations.Reference;
23import org.apache.felix.scr.annotations.ReferenceCardinality;
24import org.apache.felix.scr.annotations.Service;
25import org.apache.kafka.clients.producer.KafkaProducer;
26import org.apache.kafka.clients.producer.ProducerRecord;
27import org.apache.kafka.common.serialization.StringSerializer;
Jonathan Harta11792a2018-08-19 13:48:17 -070028import org.onosproject.cluster.ClusterService;
Jonathan Hart501f7882018-07-24 14:39:57 -070029import org.onosproject.core.ApplicationId;
30import org.onosproject.core.CoreService;
31import org.onosproject.net.config.ConfigFactory;
32import org.onosproject.net.config.NetworkConfigEvent;
33import org.onosproject.net.config.NetworkConfigListener;
34import org.onosproject.net.config.NetworkConfigRegistry;
35import org.onosproject.net.config.basics.SubjectFactories;
36import org.opencord.kafka.EventBusService;
37import org.slf4j.Logger;
38
39import java.util.Properties;
40import java.util.concurrent.ExecutorService;
Jonathan Harta11792a2018-08-19 13:48:17 -070041import java.util.concurrent.TimeUnit;
Jonathan Hart501f7882018-07-24 14:39:57 -070042
43import static com.google.common.base.Preconditions.checkNotNull;
44import static java.util.concurrent.Executors.newSingleThreadExecutor;
45import static org.onlab.util.Tools.groupedThreads;
46import static org.slf4j.LoggerFactory.getLogger;
47
48/**
49 * Sends events to a Kafka event bus.
50 */
51@Service
52@Component(immediate = true)
53public class KafkaIntegration implements EventBusService {
54
55 private final Logger log = getLogger(getClass());
56 private static final Class<KafkaConfig>
57 KAFKA_CONFIG_CLASS = KafkaConfig.class;
58
59 private static final String APP_NAME = "org.opencord.kafka";
60 private ApplicationId appId;
61
Matteo Scandolo246f7232019-05-09 15:57:39 -070062 private Boolean kafkaStarted = false;
63
Jonathan Hart501f7882018-07-24 14:39:57 -070064 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
65 protected CoreService coreService;
66
67 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Jonathan Harta11792a2018-08-19 13:48:17 -070068 protected ClusterService clusterService;
69
70 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Jonathan Hart501f7882018-07-24 14:39:57 -070071 protected NetworkConfigRegistry configRegistry;
72
73 private static StringSerializer stringSerializer = new StringSerializer();
74
75 private KafkaProducer<String, String> kafkaProducer;
76
77 private InternalNetworkConfigListener configListener =
78 new InternalNetworkConfigListener();
79
80 private final ExecutorService executor = newSingleThreadExecutor(
81 groupedThreads(this.getClass().getSimpleName(), "events", log));
82
83 private ConfigFactory<ApplicationId, KafkaConfig> kafkaConfigFactory =
84 new ConfigFactory<ApplicationId, KafkaConfig>(
85 SubjectFactories.APP_SUBJECT_FACTORY, KAFKA_CONFIG_CLASS,
86 "kafka") {
87 @Override
88 public KafkaConfig createConfig() {
89 return new KafkaConfig();
90 }
91 };
92
Jonathan Harta11792a2018-08-19 13:48:17 -070093 private static final String CLIENT_ID = "client.id";
Jonathan Hart501f7882018-07-24 14:39:57 -070094 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 TIMESTAMP = "timestamp";
106
107 @Activate
108 public void activate() {
109 appId = coreService.registerApplication(APP_NAME);
110 configRegistry.registerConfigFactory(kafkaConfigFactory);
111 configRegistry.addListener(configListener);
Andy Bavier8e9eeef2018-09-19 15:40:58 -0700112 configure();
Jonathan Hart501f7882018-07-24 14:39:57 -0700113
Jonathan Hart501f7882018-07-24 14:39:57 -0700114 log.info("Started");
115 }
116
117 @Deactivate
118 public void deactivate() {
119 configRegistry.removeListener(configListener);
120 configRegistry.unregisterConfigFactory(kafkaConfigFactory);
121
122 executor.shutdownNow();
123
124 shutdownKafka();
125 log.info("Stopped");
126 }
127
128 private void configure() {
129 KafkaConfig config =
130 configRegistry.getConfig(appId, KAFKA_CONFIG_CLASS);
131 if (config == null) {
132 log.info("Kafka configuration not present");
133 return;
134 }
135 configure(config);
136 }
137
138 private void configure(KafkaConfig config) {
139 checkNotNull(config);
140
141 Properties properties = new Properties();
Jonathan Harta11792a2018-08-19 13:48:17 -0700142 properties.put(CLIENT_ID, clusterService.getLocalNode().id().toString());
Jonathan Hart501f7882018-07-24 14:39:57 -0700143 properties.put(BOOTSTRAP_SERVERS, config.getBootstrapServers());
144 properties.put(RETRIES, config.getRetries());
145 properties.put(RECONNECT_BACKOFF, config.getReconnectBackoff());
146 properties.put(INFLIGHT_REQUESTS, config.getInflightRequests());
147 properties.put(ACKS, config.getAcks());
148 properties.put(KEY_SERIALIZER, STRING_SERIALIZER);
149 properties.put(VALUE_SERIALIZER, STRING_SERIALIZER);
150
151 startKafka(properties);
152 }
153
154 private void unconfigure() {
155 shutdownKafka();
156 }
157
158 private void startKafka(Properties properties) {
Matteo Scandolo246f7232019-05-09 15:57:39 -0700159 if (!kafkaStarted) {
160 // Kafka client doesn't play nice with the default OSGi classloader
161 // This workaround temporarily changes the thread's classloader so that
162 // the Kafka client can load the serializer classes.
163 ClassLoader original = Thread.currentThread().getContextClassLoader();
164 Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
165 try {
166 log.info("Starting Kafka producer");
167 kafkaProducer = new KafkaProducer<>(properties);
168 kafkaStarted = true;
169 } finally {
170 Thread.currentThread().setContextClassLoader(original);
171 }
Jonathan Hart501f7882018-07-24 14:39:57 -0700172 }
173 }
174
175 private void shutdownKafka() {
176 if (kafkaProducer != null) {
Jonathan Harta11792a2018-08-19 13:48:17 -0700177 log.info("Shutting down Kafka producer");
178 kafkaProducer.flush();
179 kafkaProducer.close(0, TimeUnit.MILLISECONDS);
Jonathan Hart501f7882018-07-24 14:39:57 -0700180 kafkaProducer = null;
181 }
Matteo Scandolo246f7232019-05-09 15:57:39 -0700182 kafkaStarted = false;
Jonathan Hart501f7882018-07-24 14:39:57 -0700183 }
184
185 private void logException(Exception e) {
186 if (e != null) {
187 log.error("Exception while sending to Kafka", e);
188 }
189 }
190
191 @Override
192 public void send(String topic, JsonNode data) {
193 if (kafkaProducer == null) {
Matteo Scandoloe53b12a2018-09-13 10:06:58 -0700194 log.warn("Not sending event as kafkaProducer is not defined: {}", data.toString());
Jonathan Hart501f7882018-07-24 14:39:57 -0700195 return;
196 }
197
198 if (log.isTraceEnabled()) {
199 log.trace("Sending event to Kafka: {}", data.toString());
200 }
201
202 kafkaProducer.send(new ProducerRecord<>(topic, data.toString()),
203 (r, e) -> logException(e));
204 }
205
206 private class InternalNetworkConfigListener implements NetworkConfigListener {
207
208 @Override
209 public void event(NetworkConfigEvent event) {
Jonathan Harta11792a2018-08-19 13:48:17 -0700210 log.info("Event type {}", event.type());
Jonathan Hart501f7882018-07-24 14:39:57 -0700211 switch (event.type()) {
212 case CONFIG_ADDED:
213 case CONFIG_UPDATED:
Matteo Scandolo246f7232019-05-09 15:57:39 -0700214 unconfigure();
Jonathan Hart501f7882018-07-24 14:39:57 -0700215 configure((KafkaConfig) event.config().get());
216 break;
217 case CONFIG_REMOVED:
218 unconfigure();
219 break;
220 case CONFIG_REGISTERED:
221 case CONFIG_UNREGISTERED:
222 default:
223 break;
224 }
225 }
226
227 @Override
228 public boolean isRelevant(NetworkConfigEvent event) {
229 return event.configClass().equals(KAFKA_CONFIG_CLASS);
230 }
231 }
232}