Sanjana Agarwal | cb4a3db | 2016-07-14 11:42:48 -0700 | [diff] [blame^] | 1 | /** |
| 2 | * Copyright 2016-present Open Networking Laboratory |
| 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 | */ |
| 16 | |
| 17 | package org.onosproject.kafkaintegration.kafka; |
| 18 | |
| 19 | import org.apache.felix.scr.annotations.Activate; |
| 20 | import org.apache.felix.scr.annotations.Component; |
| 21 | import org.apache.felix.scr.annotations.Deactivate; |
| 22 | import org.apache.felix.scr.annotations.Modified; |
| 23 | import org.apache.felix.scr.annotations.Property; |
| 24 | import org.apache.felix.scr.annotations.Reference; |
| 25 | import org.apache.felix.scr.annotations.ReferenceCardinality; |
| 26 | import org.apache.kafka.clients.producer.ProducerRecord; |
| 27 | import org.onosproject.cfg.ComponentConfigService; |
| 28 | import org.onosproject.kafkaintegration.api.EventConversionService; |
| 29 | import org.onosproject.kafkaintegration.api.EventSubscriptionService; |
| 30 | import org.onosproject.net.device.DeviceEvent; |
| 31 | import org.onosproject.net.device.DeviceListener; |
| 32 | import org.onosproject.net.device.DeviceService; |
| 33 | import org.onosproject.net.link.LinkEvent; |
| 34 | import org.onosproject.net.link.LinkListener; |
| 35 | import org.onosproject.net.link.LinkService; |
| 36 | import org.osgi.service.component.ComponentContext; |
| 37 | import org.slf4j.Logger; |
| 38 | import org.slf4j.LoggerFactory; |
| 39 | |
| 40 | import java.util.Dictionary; |
| 41 | import java.util.UUID; |
| 42 | import java.util.concurrent.ExecutionException; |
| 43 | import java.util.concurrent.ExecutorService; |
| 44 | |
| 45 | import static com.google.common.base.Strings.isNullOrEmpty; |
| 46 | import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; |
| 47 | import static org.onlab.util.Tools.get; |
| 48 | import static org.onlab.util.Tools.groupedThreads; |
| 49 | import static org.onosproject.kafkaintegration.api.dto.OnosEvent.Type.DEVICE; |
| 50 | import static org.onosproject.kafkaintegration.api.dto.OnosEvent.Type.LINK; |
| 51 | |
| 52 | /** |
| 53 | * Encapsulates the behavior of monitoring various ONOS events. |
| 54 | * */ |
| 55 | @Component(immediate = true) |
| 56 | public class EventMonitor { |
| 57 | private final Logger log = LoggerFactory.getLogger(getClass()); |
| 58 | |
| 59 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 60 | protected EventSubscriptionService eventSubscriptionService; |
| 61 | |
| 62 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 63 | protected EventConversionService eventConversionService; |
| 64 | |
| 65 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 66 | protected DeviceService deviceService; |
| 67 | |
| 68 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 69 | protected LinkService linkService; |
| 70 | |
| 71 | @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) |
| 72 | protected ComponentConfigService componentConfigService; |
| 73 | |
| 74 | private final DeviceListener deviceListener = new InternalDeviceListener(); |
| 75 | private final LinkListener linkListener = new InternalLinkListener(); |
| 76 | |
| 77 | protected ExecutorService eventExecutor; |
| 78 | |
| 79 | private static final String BOOTSTRAP_SERVERS = "localhost:9092"; |
| 80 | private static final int RETRIES = 1; |
| 81 | private static final int MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION = 5; |
| 82 | private static final int REQUEST_REQUIRED_ACKS = 1; |
| 83 | private static final String KEY_SERIALIZER = "org.apache.kafka.common.serialization.StringSerializer"; |
| 84 | private static final String VALUE_SERIALIZER = "org.apache.kafka.common.serialization.ByteArraySerializer"; |
| 85 | |
| 86 | @Property(name = "bootstrap.servers", value = BOOTSTRAP_SERVERS, |
| 87 | label = "Default host/post pair to establish initial connection to Kafka cluster.") |
| 88 | private String bootstrapServers = BOOTSTRAP_SERVERS; |
| 89 | |
| 90 | @Property(name = "retries", intValue = RETRIES, |
| 91 | label = "Number of times the producer can retry to send after first failure") |
| 92 | private int retries = RETRIES; |
| 93 | |
| 94 | @Property(name = "max.in.flight.requests.per.connection", intValue = MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, |
| 95 | label = "The maximum number of unacknowledged requests the client will send before blocking") |
| 96 | private int maxInFlightRequestsPerConnection = MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION; |
| 97 | |
| 98 | @Property(name = "request.required.acks", intValue = 1, |
| 99 | label = "Producer will get an acknowledgement after the leader has replicated the data") |
| 100 | private int requestRequiredAcks = REQUEST_REQUIRED_ACKS; |
| 101 | |
| 102 | @Property(name = "key.serializer", value = KEY_SERIALIZER, |
| 103 | label = "Serializer class for key that implements the Serializer interface.") |
| 104 | private String keySerializer = KEY_SERIALIZER; |
| 105 | |
| 106 | @Property(name = "value.serializer", value = VALUE_SERIALIZER, |
| 107 | label = "Serializer class for value that implements the Serializer interface.") |
| 108 | private String valueSerializer = VALUE_SERIALIZER; |
| 109 | |
| 110 | private Producer producer; |
| 111 | |
| 112 | @Activate |
| 113 | protected void activate(ComponentContext context) { |
| 114 | componentConfigService.registerProperties(getClass()); |
| 115 | eventExecutor = newSingleThreadScheduledExecutor(groupedThreads("onos/onosEvents", "events-%d", log)); |
| 116 | deviceService.addListener(deviceListener); |
| 117 | linkService.addListener(linkListener); |
| 118 | producer = new Producer(bootstrapServers, retries, maxInFlightRequestsPerConnection, |
| 119 | requestRequiredAcks, keySerializer, valueSerializer); |
| 120 | producer.start(); |
| 121 | |
| 122 | log.info("Started"); |
| 123 | } |
| 124 | |
| 125 | @Deactivate |
| 126 | protected void deactivate() { |
| 127 | componentConfigService.unregisterProperties(getClass(), false); |
| 128 | deviceService.removeListener(deviceListener); |
| 129 | linkService.removeListener(linkListener); |
| 130 | producer.stop(); |
| 131 | eventExecutor.shutdownNow(); |
| 132 | eventExecutor = null; |
| 133 | |
| 134 | log.info("Stopped"); |
| 135 | } |
| 136 | |
| 137 | @Modified |
| 138 | private void modified(ComponentContext context) { |
| 139 | if (context == null) { |
| 140 | bootstrapServers = BOOTSTRAP_SERVERS; |
| 141 | retries = RETRIES; |
| 142 | maxInFlightRequestsPerConnection = MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION; |
| 143 | requestRequiredAcks = REQUEST_REQUIRED_ACKS; |
| 144 | keySerializer = KEY_SERIALIZER; |
| 145 | valueSerializer = VALUE_SERIALIZER; |
| 146 | return; |
| 147 | } |
| 148 | Dictionary properties = context.getProperties(); |
| 149 | |
| 150 | String newBootstrapServers = BOOTSTRAP_SERVERS; |
| 151 | int newRetries = RETRIES; |
| 152 | int newMaxInFlightRequestsPerConnection = MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION; |
| 153 | int newRequestRequiredAcks = REQUEST_REQUIRED_ACKS; |
| 154 | try { |
| 155 | String s = get(properties, "bootstrapServers"); |
| 156 | newBootstrapServers = isNullOrEmpty(s) |
| 157 | ? bootstrapServers : s.trim(); |
| 158 | |
| 159 | s = get(properties, "retries"); |
| 160 | newRetries = isNullOrEmpty(s) |
| 161 | ? retries : Integer.parseInt(s.trim()); |
| 162 | |
| 163 | s = get(properties, "maxInFlightRequestsPerConnection"); |
| 164 | newMaxInFlightRequestsPerConnection = isNullOrEmpty(s) |
| 165 | ? maxInFlightRequestsPerConnection : Integer.parseInt(s.trim()); |
| 166 | |
| 167 | s = get(properties, "requestRequiredAcks"); |
| 168 | newRequestRequiredAcks = isNullOrEmpty(s) |
| 169 | ? requestRequiredAcks : Integer.parseInt(s.trim()); |
| 170 | |
| 171 | } catch (NumberFormatException | ClassCastException e) { |
| 172 | return; |
| 173 | } |
| 174 | |
| 175 | boolean modified = newBootstrapServers != bootstrapServers || |
| 176 | newRetries != retries || |
| 177 | newMaxInFlightRequestsPerConnection != maxInFlightRequestsPerConnection || |
| 178 | newRequestRequiredAcks != requestRequiredAcks; |
| 179 | |
| 180 | if (modified) { |
| 181 | bootstrapServers = newBootstrapServers; |
| 182 | retries = newRetries; |
| 183 | maxInFlightRequestsPerConnection = newMaxInFlightRequestsPerConnection; |
| 184 | requestRequiredAcks = newRequestRequiredAcks; |
| 185 | if (producer != null) { |
| 186 | producer.stop(); |
| 187 | } |
| 188 | producer = new Producer(bootstrapServers, retries, maxInFlightRequestsPerConnection, |
| 189 | requestRequiredAcks, keySerializer, valueSerializer); |
| 190 | producer.start(); |
| 191 | log.info("Modified"); |
| 192 | } else { |
| 193 | return; |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | private class InternalDeviceListener implements DeviceListener { |
| 198 | |
| 199 | @Override |
| 200 | public void event(DeviceEvent event) { |
| 201 | if (!eventSubscriptionService.getEventSubscribers(DEVICE).isEmpty()) { |
| 202 | eventExecutor.execute(() -> { |
| 203 | try { |
| 204 | String id = UUID.randomUUID().toString(); |
| 205 | producer.send(new ProducerRecord<>(DEVICE.toString(), |
| 206 | id, event.subject().toString().getBytes())).get(); |
| 207 | log.debug("Device event sent successfully."); |
| 208 | } catch (InterruptedException e) { |
| 209 | Thread.currentThread().interrupt(); |
| 210 | } catch (ExecutionException e) { |
| 211 | log.error("Exception thrown {}", e); |
| 212 | } |
| 213 | }); |
| 214 | } else { |
| 215 | log.debug("No device listeners"); |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | private class InternalLinkListener implements LinkListener { |
| 221 | |
| 222 | @Override |
| 223 | public void event(LinkEvent event) { |
| 224 | if (!eventSubscriptionService.getEventSubscribers(LINK).isEmpty()) { |
| 225 | eventExecutor.execute(() -> { |
| 226 | try { |
| 227 | String id = UUID.randomUUID().toString(); |
| 228 | producer.send(new ProducerRecord<>(LINK.toString(), |
| 229 | id, event.subject().toString().getBytes())).get(); |
| 230 | log.debug("Link event sent successfully."); |
| 231 | } catch (InterruptedException e) { |
| 232 | Thread.currentThread().interrupt(); |
| 233 | } catch (ExecutionException e) { |
| 234 | log.error("Exception thrown {}", e); |
| 235 | } |
| 236 | }); |
| 237 | } else { |
| 238 | log.debug("No link listeners"); |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | } |