blob: d6e3392a748826512f9d5ca61f4f4ad642587be7 [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);
110
Jonathan Hart501f7882018-07-24 14:39:57 -0700111 log.info("Started");
112 }
113
114 @Deactivate
115 public void deactivate() {
116 configRegistry.removeListener(configListener);
117 configRegistry.unregisterConfigFactory(kafkaConfigFactory);
118
119 executor.shutdownNow();
120
121 shutdownKafka();
122 log.info("Stopped");
123 }
124
125 private void configure() {
126 KafkaConfig config =
127 configRegistry.getConfig(appId, KAFKA_CONFIG_CLASS);
128 if (config == null) {
129 log.info("Kafka configuration not present");
130 return;
131 }
132 configure(config);
133 }
134
135 private void configure(KafkaConfig config) {
136 checkNotNull(config);
137
138 Properties properties = new Properties();
Jonathan Harta11792a2018-08-19 13:48:17 -0700139 properties.put(CLIENT_ID, clusterService.getLocalNode().id().toString());
Jonathan Hart501f7882018-07-24 14:39:57 -0700140 properties.put(BOOTSTRAP_SERVERS, config.getBootstrapServers());
141 properties.put(RETRIES, config.getRetries());
142 properties.put(RECONNECT_BACKOFF, config.getReconnectBackoff());
143 properties.put(INFLIGHT_REQUESTS, config.getInflightRequests());
144 properties.put(ACKS, config.getAcks());
145 properties.put(KEY_SERIALIZER, STRING_SERIALIZER);
146 properties.put(VALUE_SERIALIZER, STRING_SERIALIZER);
147
148 startKafka(properties);
149 }
150
151 private void unconfigure() {
152 shutdownKafka();
153 }
154
155 private void startKafka(Properties properties) {
156 shutdownKafka();
157
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 {
Jonathan Harta11792a2018-08-19 13:48:17 -0700164 log.info("Starting Kafka producer");
Jonathan Hart501f7882018-07-24 14:39:57 -0700165 kafkaProducer = new KafkaProducer<>(properties);
166 } finally {
167 Thread.currentThread().setContextClassLoader(original);
168 }
169 }
170
171 private void shutdownKafka() {
172 if (kafkaProducer != null) {
Jonathan Harta11792a2018-08-19 13:48:17 -0700173 log.info("Shutting down Kafka producer");
174 kafkaProducer.flush();
175 kafkaProducer.close(0, TimeUnit.MILLISECONDS);
Jonathan Hart501f7882018-07-24 14:39:57 -0700176 kafkaProducer = null;
177 }
178 }
179
180 private void logException(Exception e) {
181 if (e != null) {
182 log.error("Exception while sending to Kafka", e);
183 }
184 }
185
186 @Override
187 public void send(String topic, JsonNode data) {
188 if (kafkaProducer == null) {
189 return;
190 }
191
192 if (log.isTraceEnabled()) {
193 log.trace("Sending event to Kafka: {}", data.toString());
194 }
195
196 kafkaProducer.send(new ProducerRecord<>(topic, data.toString()),
197 (r, e) -> logException(e));
198 }
199
200 private class InternalNetworkConfigListener implements NetworkConfigListener {
201
202 @Override
203 public void event(NetworkConfigEvent event) {
Jonathan Harta11792a2018-08-19 13:48:17 -0700204 log.info("Event type {}", event.type());
Jonathan Hart501f7882018-07-24 14:39:57 -0700205 switch (event.type()) {
206 case CONFIG_ADDED:
207 case CONFIG_UPDATED:
208 configure((KafkaConfig) event.config().get());
209 break;
210 case CONFIG_REMOVED:
211 unconfigure();
212 break;
213 case CONFIG_REGISTERED:
214 case CONFIG_UNREGISTERED:
215 default:
216 break;
217 }
218 }
219
220 @Override
221 public boolean isRelevant(NetworkConfigEvent event) {
222 return event.configClass().equals(KAFKA_CONFIG_CLASS);
223 }
224 }
225}