blob: 3610d5018fbcb48d4f5dcf7f580563593a6d2305 [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
62 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
63 protected CoreService coreService;
64
65 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Jonathan Harta11792a2018-08-19 13:48:17 -070066 protected ClusterService clusterService;
67
68 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
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) {
157 shutdownKafka();
158
159 // Kafka client doesn't play nice with the default OSGi classloader
160 // This workaround temporarily changes the thread's classloader so that
161 // the Kafka client can load the serializer classes.
162 ClassLoader original = Thread.currentThread().getContextClassLoader();
163 Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
164 try {
Jonathan Harta11792a2018-08-19 13:48:17 -0700165 log.info("Starting Kafka producer");
Jonathan Hart501f7882018-07-24 14:39:57 -0700166 kafkaProducer = new KafkaProducer<>(properties);
167 } finally {
168 Thread.currentThread().setContextClassLoader(original);
169 }
170 }
171
172 private void shutdownKafka() {
173 if (kafkaProducer != null) {
Jonathan Harta11792a2018-08-19 13:48:17 -0700174 log.info("Shutting down Kafka producer");
175 kafkaProducer.flush();
176 kafkaProducer.close(0, TimeUnit.MILLISECONDS);
Jonathan Hart501f7882018-07-24 14:39:57 -0700177 kafkaProducer = null;
178 }
179 }
180
181 private void logException(Exception e) {
182 if (e != null) {
183 log.error("Exception while sending to Kafka", e);
184 }
185 }
186
187 @Override
188 public void send(String topic, JsonNode data) {
189 if (kafkaProducer == null) {
Matteo Scandoloe53b12a2018-09-13 10:06:58 -0700190 log.warn("Not sending event as kafkaProducer is not defined: {}", data.toString());
Jonathan Hart501f7882018-07-24 14:39:57 -0700191 return;
192 }
193
194 if (log.isTraceEnabled()) {
195 log.trace("Sending event to Kafka: {}", data.toString());
196 }
197
198 kafkaProducer.send(new ProducerRecord<>(topic, data.toString()),
199 (r, e) -> logException(e));
200 }
201
202 private class InternalNetworkConfigListener implements NetworkConfigListener {
203
204 @Override
205 public void event(NetworkConfigEvent event) {
Jonathan Harta11792a2018-08-19 13:48:17 -0700206 log.info("Event type {}", event.type());
Jonathan Hart501f7882018-07-24 14:39:57 -0700207 switch (event.type()) {
208 case CONFIG_ADDED:
209 case CONFIG_UPDATED:
210 configure((KafkaConfig) event.config().get());
211 break;
212 case CONFIG_REMOVED:
213 unconfigure();
214 break;
215 case CONFIG_REGISTERED:
216 case CONFIG_UNREGISTERED:
217 default:
218 break;
219 }
220 }
221
222 @Override
223 public boolean isRelevant(NetworkConfigEvent event) {
224 return event.configClass().equals(KAFKA_CONFIG_CLASS);
225 }
226 }
227}