blob: 7d0be644539d5390a7e4d6dd34af4936e50c6ffc [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 Open Networking Laboratory
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07003 *
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 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.store.device.impl;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070017
Yuta HIGUCHI47c40882014-10-10 18:44:37 -070018import com.google.common.base.Function;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070019import com.google.common.collect.FluentIterable;
20import com.google.common.collect.ImmutableList;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -070021import com.google.common.collect.Maps;
22import com.google.common.collect.Sets;
Dusan Pajin11ff4a82015-08-20 18:03:05 +020023
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070024import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070025import org.apache.felix.scr.annotations.Activate;
26import org.apache.felix.scr.annotations.Component;
27import org.apache.felix.scr.annotations.Deactivate;
28import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
30import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080031import org.onlab.packet.ChassisId;
32import org.onlab.util.KryoNamespace;
33import org.onlab.util.NewConcurrentHashMap;
Brian O'Connorabafb502014-12-02 22:26:20 -080034import org.onosproject.cluster.ClusterService;
35import org.onosproject.cluster.ControllerNode;
36import org.onosproject.cluster.NodeId;
37import org.onosproject.mastership.MastershipService;
38import org.onosproject.mastership.MastershipTerm;
39import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070040import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080041import org.onosproject.net.AnnotationsUtil;
42import org.onosproject.net.DefaultAnnotations;
43import org.onosproject.net.DefaultDevice;
44import org.onosproject.net.DefaultPort;
45import org.onosproject.net.Device;
46import org.onosproject.net.Device.Type;
47import org.onosproject.net.DeviceId;
48import org.onosproject.net.MastershipRole;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070049import org.onosproject.net.OchPort;
50import org.onosproject.net.OduCltPort;
51import org.onosproject.net.OmsPort;
Brian O'Connorabafb502014-12-02 22:26:20 -080052import org.onosproject.net.Port;
53import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070054import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.net.device.DeviceClockService;
56import org.onosproject.net.device.DeviceDescription;
57import org.onosproject.net.device.DeviceEvent;
58import org.onosproject.net.device.DeviceStore;
59import org.onosproject.net.device.DeviceStoreDelegate;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070060import org.onosproject.net.device.OchPortDescription;
61import org.onosproject.net.device.OduCltPortDescription;
62import org.onosproject.net.device.OmsPortDescription;
Brian O'Connorabafb502014-12-02 22:26:20 -080063import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070064import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080065import org.onosproject.net.provider.ProviderId;
66import org.onosproject.store.AbstractStore;
67import org.onosproject.store.Timestamp;
68import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
69import org.onosproject.store.cluster.messaging.ClusterMessage;
70import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
71import org.onosproject.store.cluster.messaging.MessageSubject;
72import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070073import org.onosproject.store.serializers.KryoNamespaces;
Brian O'Connorabafb502014-12-02 22:26:20 -080074import org.onosproject.store.serializers.KryoSerializer;
Brian O'Connor6de2e202015-05-21 14:30:41 -070075import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070076import org.onosproject.store.service.EventuallyConsistentMap;
77import org.onosproject.store.service.EventuallyConsistentMapEvent;
78import org.onosproject.store.service.EventuallyConsistentMapListener;
79import org.onosproject.store.service.MultiValuedTimestamp;
80import org.onosproject.store.service.StorageService;
81import org.onosproject.store.service.WallClockTimestamp;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070082import org.slf4j.Logger;
83
Madan Jampani47c93732014-10-06 20:46:08 -070084import java.io.IOException;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070085import java.util.ArrayList;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070086import java.util.Collection;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070087import java.util.Collections;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070088import java.util.HashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070089import java.util.HashSet;
90import java.util.Iterator;
91import java.util.List;
92import java.util.Map;
93import java.util.Map.Entry;
94import java.util.Objects;
95import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070096import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080097import java.util.concurrent.ExecutorService;
98import java.util.concurrent.Executors;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070099import java.util.concurrent.ScheduledExecutorService;
100import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700101
102import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700103import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700104import static com.google.common.base.Verify.verify;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800105import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
106import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800107import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800108import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800109import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
110import static org.onosproject.net.DefaultAnnotations.merge;
111import static org.onosproject.net.device.DeviceEvent.Type.*;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800112import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700113import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800114import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700115
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700116/**
117 * Manages inventory of infrastructure devices using gossip protocol to distribute
118 * information.
119 */
120@Component(immediate = true)
121@Service
122public class GossipDeviceStore
123 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
124 implements DeviceStore {
125
126 private final Logger log = getLogger(getClass());
127
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700128 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800129 // Timeout in milliseconds to process device or ports on remote master node
130 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700131
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700132 // innerMap is used to lock a Device, thus instance should never be replaced.
133 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700134 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700135 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700136
137 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700138 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
139 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700140
141 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200142 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700143 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
144 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700145
146 // to be updated under Device lock
147 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
148 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700149
150 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700151 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700152
153 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700154 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700155
Madan Jampani47c93732014-10-06 20:46:08 -0700156 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700157 protected StorageService storageService;
158
159 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700160 protected ClusterCommunicationService clusterCommunicator;
161
Madan Jampani53e44e62014-10-07 12:39:51 -0700162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
163 protected ClusterService clusterService;
164
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
166 protected MastershipService mastershipService;
167
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800168 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
169 protected MastershipTermService termService;
170
171
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700172 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700173 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700174 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700175 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800176 .register(DistributedStoreSerializers.STORE_COMMON)
177 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
178 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
179 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700180 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800181 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
182 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700183 .register(DeviceAntiEntropyAdvertisement.class)
184 .register(DeviceFragmentId.class)
185 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800186 .register(DeviceInjectedEvent.class)
187 .register(PortInjectedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800188 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700189 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700190 };
191
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800192 private ExecutorService executor;
193
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800194 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700195
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800196 // TODO make these anti-entropy parameters configurable
197 private long initialDelaySec = 5;
198 private long periodSec = 5;
199
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700200 @Activate
201 public void activate() {
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800202 executor = Executors.newCachedThreadPool(groupedThreads("onos/device", "fg-%d"));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800203
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800204 backgroundExecutor =
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800205 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700206
Madan Jampani2af244a2015-02-22 13:12:01 -0800207 clusterCommunicator.addSubscriber(
208 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
209 clusterCommunicator.addSubscriber(
210 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
211 new InternalDeviceOfflineEventListener(),
212 executor);
213 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700214 new InternalRemoveRequestListener(),
215 executor);
Madan Jampani2af244a2015-02-22 13:12:01 -0800216 clusterCommunicator.addSubscriber(
217 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
218 clusterCommunicator.addSubscriber(
219 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
220 clusterCommunicator.addSubscriber(
221 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
222 clusterCommunicator.addSubscriber(
223 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
224 new InternalDeviceAdvertisementListener(),
225 backgroundExecutor);
226 clusterCommunicator.addSubscriber(
227 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
228 clusterCommunicator.addSubscriber(
229 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
230
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700231 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800232 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700233 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700234
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700235 // Create a distributed map for port stats.
236 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
237 .register(KryoNamespaces.API)
238 .register(DefaultPortStatistics.class)
239 .register(DeviceId.class)
240 .register(MultiValuedTimestamp.class)
241 .register(WallClockTimestamp.class);
242
243 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
244 .withName("port-stats")
245 .withSerializer(deviceDataSerializer)
246 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700247 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700248 .withTombstonesDisabled()
249 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200250 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
251 eventuallyConsistentMapBuilder()
252 .withName("port-stats-delta")
253 .withSerializer(deviceDataSerializer)
254 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
255 .withTimestampProvider((k, v) -> new WallClockTimestamp())
256 .withTombstonesDisabled()
257 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700258 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700259 log.info("Started");
260 }
261
262 @Deactivate
263 public void deactivate() {
Madan Jampani632f16b2015-08-11 12:42:59 -0700264 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200265 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800266 executor.shutdownNow();
267
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800268 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700269 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800270 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700271 log.error("Timeout during executor shutdown");
272 }
273 } catch (InterruptedException e) {
274 log.error("Error during executor shutdown", e);
275 }
276
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700277 deviceDescs.clear();
278 devices.clear();
279 devicePorts.clear();
280 availableDevices.clear();
281 log.info("Stopped");
282 }
283
284 @Override
285 public int getDeviceCount() {
286 return devices.size();
287 }
288
289 @Override
290 public Iterable<Device> getDevices() {
291 return Collections.unmodifiableCollection(devices.values());
292 }
293
294 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800295 public Iterable<Device> getAvailableDevices() {
296 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700297 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800298 }
299
300 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700301 public Device getDevice(DeviceId deviceId) {
302 return devices.get(deviceId);
303 }
304
305 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700306 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700307 DeviceId deviceId,
308 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800309 NodeId localNode = clusterService.getLocalNode().id();
310 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
311
312 // Process device update only if we're the master,
313 // otherwise signal the actual master.
314 DeviceEvent deviceEvent = null;
315 if (localNode.equals(deviceNode)) {
316
317 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
318 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
319 final Timestamped<DeviceDescription> mergedDesc;
320 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
321
322 synchronized (device) {
323 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
324 mergedDesc = device.get(providerId).getDeviceDesc();
325 }
326
327 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700328 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700329 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800330 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
331 }
332
333 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800334 // FIXME Temporary hack for NPE (ONOS-1171).
335 // Proper fix is to implement forwarding to master on ConfigProvider
336 // redo ONOS-490
337 if (deviceNode == null) {
338 // silently ignore
339 return null;
340 }
341
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800342
343 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
344 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800345
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800346 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700347 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800348 /* error log:
349 log.warn("Failed to process injected device id: {} desc: {} " +
350 "(cluster messaging failed: {})",
351 deviceId, deviceDescription, e);
352 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700353 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800354
355 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700356 }
357
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700358 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700359 DeviceId deviceId,
360 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700361
362 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800363 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700364 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700365
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800366 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700367 // locking per device
368
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700369 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
370 log.debug("Ignoring outdated event: {}", deltaDesc);
371 return null;
372 }
373
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800374 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700375
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700376 final Device oldDevice = devices.get(deviceId);
377 final Device newDevice;
378
379 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700380 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700381 // on new device or valid update
382 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800383 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700384 } else {
385 // outdated event, ignored.
386 return null;
387 }
388 if (oldDevice == null) {
389 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700390 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700391 } else {
392 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700393 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700394 }
395 }
396 }
397
398 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700399 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700400 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700401 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700402
403 // update composed device cache
404 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
405 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700406 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
407 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700408
409 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700410 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700411 }
412
413 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
414 }
415
416 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700417 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700418 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700419 Device oldDevice,
420 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700421 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700422 boolean propertiesChanged =
423 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700424 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
425 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700426 boolean annotationsChanged =
427 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700428
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700429 // Primary providers can respond to all changes, but ancillary ones
430 // should respond only to annotation changes.
431 if ((providerId.isAncillary() && annotationsChanged) ||
432 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700433 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
434 if (!replaced) {
435 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700436 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
437 providerId, oldDevice, devices.get(newDevice.id())
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700438 , newDevice);
439 }
440 if (!providerId.isAncillary()) {
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700441 boolean wasOnline = availableDevices.contains(newDevice.id());
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700442 markOnline(newDevice.id(), newTimestamp);
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700443 if (!wasOnline) {
444 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
445 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700446 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700447
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700448 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700449 }
450 return null;
451 }
452
453 @Override
454 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700455 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700456 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700457 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700458 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700459 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800460 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700461 }
462 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700463 }
464
465 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
466
467 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700468 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700469
470 // locking device
471 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700472
473 // accept off-line if given timestamp is newer than
474 // the latest Timestamp from Primary provider
475 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
476 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
477 if (timestamp.compareTo(lastTimestamp) <= 0) {
478 // outdated event ignore
479 return null;
480 }
481
482 offline.put(deviceId, timestamp);
483
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700484 Device device = devices.get(deviceId);
485 if (device == null) {
486 return null;
487 }
488 boolean removed = availableDevices.remove(deviceId);
489 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700490 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700491 }
492 return null;
493 }
494 }
495
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700496 /**
497 * Marks the device as available if the given timestamp is not outdated,
498 * compared to the time the device has been marked offline.
499 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700500 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700501 * @param timestamp of the event triggering this change.
502 * @return true if availability change request was accepted and changed the state
503 */
504 // Guarded by deviceDescs value (=Device lock)
505 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
506 // accept on-line if given timestamp is newer than
507 // the latest offline request Timestamp
508 Timestamp offlineTimestamp = offline.get(deviceId);
509 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700510 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700511
512 offline.remove(deviceId);
513 return availableDevices.add(deviceId);
514 }
515 return false;
516 }
517
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700518 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700519 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700520 DeviceId deviceId,
521 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700522
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800523 NodeId localNode = clusterService.getLocalNode().id();
524 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
525 // since it will trigger distributed store read.
526 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
527 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
528 // If we don't care much about topology performance, then it might be OK.
529 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700530
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800531 // Process port update only if we're the master of the device,
532 // otherwise signal the actual master.
533 List<DeviceEvent> deviceEvents = null;
534 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700535
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800536 final Timestamp newTimestamp;
537 try {
538 newTimestamp = deviceClockService.getTimestamp(deviceId);
539 } catch (IllegalStateException e) {
540 log.info("Timestamp was not available for device {}", deviceId);
541 log.debug(" discarding {}", portDescriptions);
542 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700543
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800544 // Possible situation:
545 // Device connected and became master for short period of time,
546 // but lost mastership before this instance had the chance to
547 // retrieve term information.
548
549 // Information dropped here is expected to be recoverable by
550 // device probing after mastership change
551
552 return Collections.emptyList();
553 }
554 log.debug("timestamp for {} {}", deviceId, newTimestamp);
555
556 final Timestamped<List<PortDescription>> timestampedInput
557 = new Timestamped<>(portDescriptions, newTimestamp);
558 final Timestamped<List<PortDescription>> merged;
559
560 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
561
562 synchronized (device) {
563 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
564 final DeviceDescriptions descs = device.get(providerId);
565 List<PortDescription> mergedList =
566 FluentIterable.from(portDescriptions)
567 .transform(new Function<PortDescription, PortDescription>() {
568 @Override
569 public PortDescription apply(PortDescription input) {
570 // lookup merged port description
571 return descs.getPortDesc(input.portNumber()).value();
572 }
573 }).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700574 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800575 }
576
577 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700578 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700579 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800580 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
581 }
582
583 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800584 // FIXME Temporary hack for NPE (ONOS-1171).
585 // Proper fix is to implement forwarding to master on ConfigProvider
586 // redo ONOS-490
587 if (deviceNode == null) {
588 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800589 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800590 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800591
592 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800593
594 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700595 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800596 /* error log:
597 log.warn("Failed to process injected ports of device id: {} " +
598 "(cluster messaging failed: {})",
599 deviceId, e);
600 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700601 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700602
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800603 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700604 }
605
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700606 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700607 DeviceId deviceId,
608 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700609
610 Device device = devices.get(deviceId);
611 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
612
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700613 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700614 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
615
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700616 List<DeviceEvent> events = new ArrayList<>();
617 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700618
619 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
620 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700621 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700622 }
623
624 DeviceDescriptions descs = descsMap.get(providerId);
625 // every provider must provide DeviceDescription.
626 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700627 "Device description for Device ID %s from Provider %s was not found",
628 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700629
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700630 Map<PortNumber, Port> ports = getPortMap(deviceId);
631
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700632 final Timestamp newTimestamp = portDescriptions.timestamp();
633
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700634 // Add new ports
635 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700636 for (PortDescription portDescription : portDescriptions.value()) {
637 final PortNumber number = portDescription.portNumber();
638 processed.add(number);
639
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700640 final Port oldPort = ports.get(number);
641 final Port newPort;
642
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700643
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700644 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
645 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700646 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700647 // on new port or valid update
648 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700649 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700650 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700651 newPort = composePort(device, number, descsMap);
652 } else {
653 // outdated event, ignored.
654 continue;
655 }
656
657 events.add(oldPort == null ?
658 createPort(device, newPort, ports) :
659 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700660 }
661
662 events.addAll(pruneOldPorts(device, ports, processed));
663 }
664 return FluentIterable.from(events).filter(notNull()).toList();
665 }
666
667 // Creates a new port based on the port description adds it to the map and
668 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700669 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700670 private DeviceEvent createPort(Device device, Port newPort,
671 Map<PortNumber, Port> ports) {
672 ports.put(newPort.number(), newPort);
673 return new DeviceEvent(PORT_ADDED, device, newPort);
674 }
675
676 // Checks if the specified port requires update and if so, it replaces the
677 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700678 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700679 private DeviceEvent updatePort(Device device, Port oldPort,
680 Port newPort,
681 Map<PortNumber, Port> ports) {
682 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700683 oldPort.type() != newPort.type() ||
684 oldPort.portSpeed() != newPort.portSpeed() ||
685 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700686 ports.put(oldPort.number(), newPort);
687 return new DeviceEvent(PORT_UPDATED, device, newPort);
688 }
689 return null;
690 }
691
692 // Prunes the specified list of ports based on which ports are in the
693 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700694 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700695 private List<DeviceEvent> pruneOldPorts(Device device,
696 Map<PortNumber, Port> ports,
697 Set<PortNumber> processed) {
698 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700699 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700700 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700701 Entry<PortNumber, Port> e = iterator.next();
702 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700703 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700704 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700705 iterator.remove();
706 }
707 }
708 return events;
709 }
710
711 // Gets the map of ports for the specified device; if one does not already
712 // exist, it creates and registers a new one.
713 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
714 return createIfAbsentUnchecked(devicePorts, deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700715 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700716 }
717
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700718 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700719 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700720 Map<ProviderId, DeviceDescriptions> r;
721 r = deviceDescs.get(deviceId);
722 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700723 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700724 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
725 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
726 if (concurrentlyAdded != null) {
727 r = concurrentlyAdded;
728 }
729 }
730 return r;
731 }
732
733 // Guarded by deviceDescs value (=Device lock)
734 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
735 Map<ProviderId, DeviceDescriptions> device,
736 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700737 synchronized (device) {
738 DeviceDescriptions r = device.get(providerId);
739 if (r == null) {
740 r = new DeviceDescriptions(deltaDesc);
741 device.put(providerId, r);
742 }
743 return r;
744 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700745 }
746
747 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700748 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
749 DeviceId deviceId,
750 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700751 final Timestamp newTimestamp;
752 try {
753 newTimestamp = deviceClockService.getTimestamp(deviceId);
754 } catch (IllegalStateException e) {
755 log.info("Timestamp was not available for device {}", deviceId);
756 log.debug(" discarding {}", portDescription);
757 // Failed to generate timestamp. Ignoring.
758 // See updatePorts comment
759 return null;
760 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700761 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700762 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700763 final DeviceEvent event;
764 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800765 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
766 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700767 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800768 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700769 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700770 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700771 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700772 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700773 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800774 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700775 }
776 return event;
777 }
778
779 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700780 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700781 Device device = devices.get(deviceId);
782 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
783
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700784 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700785 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
786
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700787 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700788
789 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
790 log.debug("Ignoring outdated event: {}", deltaDesc);
791 return null;
792 }
793
794 DeviceDescriptions descs = descsMap.get(providerId);
795 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700796 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700797 "Device description for Device ID %s from Provider %s was not found",
798 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700799
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700800 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
801 final PortNumber number = deltaDesc.value().portNumber();
802 final Port oldPort = ports.get(number);
803 final Port newPort;
804
805 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
806 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700807 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700808 // on new port or valid update
809 // update description
810 descs.putPortDesc(deltaDesc);
811 newPort = composePort(device, number, descsMap);
812 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700813 // same or outdated event, ignored.
814 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700815 return null;
816 }
817
818 if (oldPort == null) {
819 return createPort(device, newPort, ports);
820 } else {
821 return updatePort(device, oldPort, newPort, ports);
822 }
823 }
824 }
825
826 @Override
827 public List<Port> getPorts(DeviceId deviceId) {
828 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
829 if (ports == null) {
830 return Collections.emptyList();
831 }
832 return ImmutableList.copyOf(ports.values());
833 }
834
835 @Override
sangho538108b2015-04-08 14:29:20 -0700836 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200837 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700838
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200839 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
840 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
841 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
842
843 if (prvStatsMap != null) {
844 for (PortStatistics newStats : newStatsCollection) {
845 PortNumber port = PortNumber.portNumber(newStats.port());
846 PortStatistics prvStats = prvStatsMap.get(port);
847 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
848 PortStatistics deltaStats = builder.build();
849 if (prvStats != null) {
850 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
851 }
852 deltaStatsMap.put(port, deltaStats);
853 newStatsMap.put(port, newStats);
854 }
855 } else {
856 for (PortStatistics newStats : newStatsCollection) {
857 PortNumber port = PortNumber.portNumber(newStats.port());
858 newStatsMap.put(port, newStats);
859 }
sangho538108b2015-04-08 14:29:20 -0700860 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200861 devicePortDeltaStats.put(deviceId, deltaStatsMap);
862 devicePortStats.put(deviceId, newStatsMap);
863 return new DeviceEvent(PORT_STATS_UPDATED, devices.get(deviceId), null);
864 }
865
866 /**
867 * Calculate delta statistics by subtracting previous from new statistics.
868 *
869 * @param deviceId
870 * @param prvStats
871 * @param newStats
872 * @return PortStatistics
873 */
874 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
875 // calculate time difference
876 long deltaStatsSec, deltaStatsNano;
877 if (newStats.durationNano() < prvStats.durationNano()) {
878 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
879 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
880 } else {
881 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
882 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
883 }
884 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
885 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
886 .setPort(newStats.port())
887 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
888 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
889 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
890 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
891 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
892 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
893 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
894 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
895 .setDurationSec(deltaStatsSec)
896 .setDurationNano(deltaStatsNano)
897 .build();
898 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700899 }
900
901 @Override
902 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700903 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
904 if (portStats == null) {
905 return Collections.emptyList();
906 }
907 return ImmutableList.copyOf(portStats.values());
908 }
909
910 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200911 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
912 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
913 if (portStats == null) {
914 return Collections.emptyList();
915 }
916 return ImmutableList.copyOf(portStats.values());
917 }
918
919 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700920 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
921 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
922 return ports == null ? null : ports.get(portNumber);
923 }
924
925 @Override
926 public boolean isAvailable(DeviceId deviceId) {
927 return availableDevices.contains(deviceId);
928 }
929
930 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700931 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800932 final NodeId myId = clusterService.getLocalNode().id();
933 NodeId master = mastershipService.getMasterFor(deviceId);
934
935 // if there exist a master, forward
936 // if there is no master, try to become one and process
937
938 boolean relinquishAtEnd = false;
939 if (master == null) {
940 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
941 if (myRole != MastershipRole.NONE) {
942 relinquishAtEnd = true;
943 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800944 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800945 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800946 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700947 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800948 master = myId;
949 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700950 }
951
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800952 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800953 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700954 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800955
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800956 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700957 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800958 /* error log:
959 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
960 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800961
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800962 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700963 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800964 }
965
966 // I have control..
967
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700968 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700969 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700970 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800971 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700972 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800973 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700974 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800975 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800976 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800977 mastershipService.relinquishMastership(deviceId);
978 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700979 return event;
980 }
981
982 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
983 Timestamp timestamp) {
984
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700985 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700986 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700987 // accept removal request if given timestamp is newer than
988 // the latest Timestamp from Primary provider
989 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
990 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
991 if (timestamp.compareTo(lastTimestamp) <= 0) {
992 // outdated event ignore
993 return null;
994 }
995 removalRequest.put(deviceId, timestamp);
996
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700997 Device device = devices.remove(deviceId);
998 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700999 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1000 if (ports != null) {
1001 ports.clear();
1002 }
1003 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001004 descs.clear();
1005 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001006 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001007 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001008 }
1009
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001010 /**
1011 * Checks if given timestamp is superseded by removal request
1012 * with more recent timestamp.
1013 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001014 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001015 * @param timestampToCheck timestamp of an event to check
1016 * @return true if device is already removed
1017 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001018 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1019 Timestamp removalTimestamp = removalRequest.get(deviceId);
1020 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001021 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001022 // removalRequest is more recent
1023 return true;
1024 }
1025 return false;
1026 }
1027
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001028 /**
1029 * Returns a Device, merging description given from multiple Providers.
1030 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001031 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001032 * @param providerDescs Collection of Descriptions from multiple providers
1033 * @return Device instance
1034 */
1035 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001036 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001037
Thomas Vachuska444eda62014-10-28 13:09:42 -07001038 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001039
1040 ProviderId primary = pickPrimaryPID(providerDescs);
1041
1042 DeviceDescriptions desc = providerDescs.get(primary);
1043
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001044 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001045 Type type = base.type();
1046 String manufacturer = base.manufacturer();
1047 String hwVersion = base.hwVersion();
1048 String swVersion = base.swVersion();
1049 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001050 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001051 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1052 annotations = merge(annotations, base.annotations());
1053
1054 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1055 if (e.getKey().equals(primary)) {
1056 continue;
1057 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001058 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001059 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001060 // Currently assuming there will never be a key conflict between
1061 // providers
1062
1063 // annotation merging. not so efficient, should revisit later
1064 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1065 }
1066
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001067 return new DefaultDevice(primary, deviceId, type, manufacturer,
1068 hwVersion, swVersion, serialNumber,
1069 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001070 }
1071
Marc De Leenheer88194c32015-05-29 22:10:59 -07001072 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1073 PortDescription description, Annotations annotations) {
1074 switch (description.type()) {
1075 case OMS:
1076 OmsPortDescription omsDesc = (OmsPortDescription) description;
1077 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1078 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1079 case OCH:
1080 OchPortDescription ochDesc = (OchPortDescription) description;
1081 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1082 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1083 case ODUCLT:
1084 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1085 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1086 default:
1087 return new DefaultPort(device, number, isEnabled, description.type(),
1088 description.portSpeed(), annotations);
1089 }
1090 }
1091
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001092 /**
1093 * Returns a Port, merging description given from multiple Providers.
1094 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001095 * @param device device the port is on
1096 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001097 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001098 * @return Port instance
1099 */
1100 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001101 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001102
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001103 ProviderId primary = pickPrimaryPID(descsMap);
1104 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001105 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001106 boolean isEnabled = false;
1107 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001108 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001109 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1110 if (portDesc != null) {
1111 isEnabled = portDesc.value().isEnabled();
1112 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001113 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001114 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001115 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001116 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001117 if (e.getKey().equals(primary)) {
1118 continue;
1119 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001120 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001121 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001122 // Currently assuming there will never be a key conflict between
1123 // providers
1124
1125 // annotation merging. not so efficient, should revisit later
1126 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1127 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001128 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1129 continue;
1130 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001131 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001132 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001133 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001134 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001135 }
1136 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001137 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001138 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001139 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001140 PortDescription current = portDesc.value();
1141 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001142 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001143 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001144 }
1145
1146 /**
1147 * @return primary ProviderID, or randomly chosen one if none exists
1148 */
1149 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001150 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001151 ProviderId fallBackPrimary = null;
1152 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1153 if (!e.getKey().isAncillary()) {
1154 return e.getKey();
1155 } else if (fallBackPrimary == null) {
1156 // pick randomly as a fallback in case there is no primary
1157 fallBackPrimary = e.getKey();
1158 }
1159 }
1160 return fallBackPrimary;
1161 }
1162
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001163 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001164 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001165 ProviderId pid = pickPrimaryPID(providerDescs);
1166 return providerDescs.get(pid);
1167 }
1168
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001169 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001170 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001171 }
1172
Jonathan Hart7d656f42015-01-27 14:07:23 -08001173 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001174 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001175 }
Madan Jampani47c93732014-10-06 20:46:08 -07001176
Jonathan Hart7d656f42015-01-27 14:07:23 -08001177 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001178 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001179 }
1180
Jonathan Hart7d656f42015-01-27 14:07:23 -08001181 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001182 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001183 }
1184
Jonathan Hart7d656f42015-01-27 14:07:23 -08001185 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001186 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001187 }
1188
Jonathan Hart7d656f42015-01-27 14:07:23 -08001189 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001190 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001191 }
1192
Jonathan Hart7d656f42015-01-27 14:07:23 -08001193 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001194 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1195 }
1196
1197 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1198 try {
1199 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1200 } catch (IOException e) {
1201 log.error("Failed to send" + event + " to " + recipient, e);
1202 }
1203 }
1204
1205 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1206 try {
1207 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1208 } catch (IOException e) {
1209 log.error("Failed to send" + event + " to " + recipient, e);
1210 }
1211 }
1212
1213 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1214 try {
1215 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1216 } catch (IOException e) {
1217 log.error("Failed to send" + event + " to " + recipient, e);
1218 }
1219 }
1220
1221 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1222 try {
1223 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1224 } catch (IOException e) {
1225 log.error("Failed to send" + event + " to " + recipient, e);
1226 }
1227 }
1228
1229 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1230 try {
1231 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1232 } catch (IOException e) {
1233 log.error("Failed to send" + event + " to " + recipient, e);
1234 }
1235 }
1236
1237 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1238 final NodeId self = clusterService.getLocalNode().id();
1239
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001240 final int numDevices = deviceDescs.size();
1241 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1242 final int portsPerDevice = 8; // random factor to minimize reallocation
1243 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1244 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001245
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001246 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001247
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001248 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001249 synchronized (devDescs) {
1250
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001251 // send device offline timestamp
1252 Timestamp lOffline = this.offline.get(deviceId);
1253 if (lOffline != null) {
1254 adOffline.put(deviceId, lOffline);
1255 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001256
1257 for (Entry<ProviderId, DeviceDescriptions>
1258 prov : devDescs.entrySet()) {
1259
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001260 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001261 final ProviderId provId = prov.getKey();
1262 final DeviceDescriptions descs = prov.getValue();
1263
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001264 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001265 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001266
1267 for (Entry<PortNumber, Timestamped<PortDescription>>
1268 portDesc : descs.getPortDescs().entrySet()) {
1269
1270 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001271 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001272 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001273 }
1274 }
1275 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001276 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001277
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001278 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001279 }
1280
1281 /**
1282 * Responds to anti-entropy advertisement message.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001283 * <p/>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001284 * Notify sender about out-dated information using regular replication message.
1285 * Send back advertisement to sender if not in sync.
1286 *
1287 * @param advertisement to respond to
1288 */
1289 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1290
1291 final NodeId sender = advertisement.sender();
1292
1293 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1294 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1295 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1296
1297 // Fragments to request
1298 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1299 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1300
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001301 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001302 final DeviceId deviceId = de.getKey();
1303 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1304
1305 synchronized (lDevice) {
1306 // latestTimestamp across provider
1307 // Note: can be null initially
1308 Timestamp localLatest = offline.get(deviceId);
1309
1310 // handle device Ads
1311 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1312 final ProviderId provId = prov.getKey();
1313 final DeviceDescriptions lDeviceDescs = prov.getValue();
1314
1315 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1316
1317
1318 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1319 Timestamp advDevTimestamp = devAds.get(devFragId);
1320
Jonathan Hart403ea932015-02-20 16:23:00 -08001321 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1322 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001323 // remote does not have it or outdated, suggest
1324 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1325 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1326 // local is outdated, request
1327 reqDevices.add(devFragId);
1328 }
1329
1330 // handle port Ads
1331 for (Entry<PortNumber, Timestamped<PortDescription>>
1332 pe : lDeviceDescs.getPortDescs().entrySet()) {
1333
1334 final PortNumber num = pe.getKey();
1335 final Timestamped<PortDescription> lPort = pe.getValue();
1336
1337 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1338
1339 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001340 if (advPortTimestamp == null || lPort.isNewerThan(
1341 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001342 // remote does not have it or outdated, suggest
1343 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1344 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1345 // local is outdated, request
1346 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1347 reqPorts.add(portFragId);
1348 }
1349
1350 // remove port Ad already processed
1351 portAds.remove(portFragId);
1352 } // end local port loop
1353
1354 // remove device Ad already processed
1355 devAds.remove(devFragId);
1356
1357 // find latest and update
1358 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1359 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001360 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001361 localLatest = providerLatest;
1362 }
1363 } // end local provider loop
1364
1365 // checking if remote timestamp is more recent.
1366 Timestamp rOffline = offlineAds.get(deviceId);
1367 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001368 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001369 // remote offline timestamp suggests that the
1370 // device is off-line
1371 markOfflineInternal(deviceId, rOffline);
1372 }
1373
1374 Timestamp lOffline = offline.get(deviceId);
1375 if (lOffline != null && rOffline == null) {
1376 // locally offline, but remote is online, suggest offline
1377 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1378 }
1379
1380 // remove device offline Ad already processed
1381 offlineAds.remove(deviceId);
1382 } // end local device loop
1383 } // device lock
1384
1385 // If there is any Ads left, request them
1386 log.trace("Ads left {}, {}", devAds, portAds);
1387 reqDevices.addAll(devAds.keySet());
1388 reqPorts.addAll(portAds.keySet());
1389
1390 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1391 log.trace("Nothing to request to remote peer {}", sender);
1392 return;
1393 }
1394
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001395 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001396
1397 // 2-way Anti-Entropy for now
1398 try {
1399 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1400 } catch (IOException e) {
1401 log.error("Failed to send response advertisement to " + sender, e);
1402 }
1403
1404// Sketch of 3-way Anti-Entropy
1405// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1406// ClusterMessage message = new ClusterMessage(
1407// clusterService.getLocalNode().id(),
1408// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1409// SERIALIZER.encode(request));
1410//
1411// try {
1412// clusterCommunicator.unicast(message, advertisement.sender());
1413// } catch (IOException e) {
1414// log.error("Failed to send advertisement reply to "
1415// + advertisement.sender(), e);
1416// }
Madan Jampani47c93732014-10-06 20:46:08 -07001417 }
1418
Madan Jampani255a58b2014-10-09 12:08:20 -07001419 private void notifyDelegateIfNotNull(DeviceEvent event) {
1420 if (event != null) {
1421 notifyDelegate(event);
1422 }
1423 }
1424
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001425 private final class SendAdvertisementTask implements Runnable {
1426
1427 @Override
1428 public void run() {
1429 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001430 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001431 return;
1432 }
1433
1434 try {
1435 final NodeId self = clusterService.getLocalNode().id();
1436 Set<ControllerNode> nodes = clusterService.getNodes();
1437
1438 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1439 .transform(toNodeId())
1440 .toList();
1441
1442 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001443 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001444 return;
1445 }
1446
1447 NodeId peer;
1448 do {
1449 int idx = RandomUtils.nextInt(0, nodeIds.size());
1450 peer = nodeIds.get(idx);
1451 } while (peer.equals(self));
1452
1453 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1454
1455 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001456 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001457 return;
1458 }
1459
1460 try {
1461 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1462 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001463 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001464 return;
1465 }
1466 } catch (Exception e) {
1467 // catch all Exception to avoid Scheduled task being suppressed.
1468 log.error("Exception thrown while sending advertisement", e);
1469 }
1470 }
1471 }
1472
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001473 private final class InternalDeviceEventListener
1474 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001475 @Override
1476 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001477 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001478 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001479
Madan Jampani47c93732014-10-06 20:46:08 -07001480 ProviderId providerId = event.providerId();
1481 DeviceId deviceId = event.deviceId();
1482 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001483
Madan Jampani2af244a2015-02-22 13:12:01 -08001484 try {
1485 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1486 } catch (Exception e) {
1487 log.warn("Exception thrown handling device update", e);
1488 }
Madan Jampani47c93732014-10-06 20:46:08 -07001489 }
1490 }
1491
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001492 private final class InternalDeviceOfflineEventListener
1493 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001494 @Override
1495 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001496 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001497 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001498
1499 DeviceId deviceId = event.deviceId();
1500 Timestamp timestamp = event.timestamp();
1501
Madan Jampani2af244a2015-02-22 13:12:01 -08001502 try {
1503 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1504 } catch (Exception e) {
1505 log.warn("Exception thrown handling device offline", e);
1506 }
Madan Jampani25322532014-10-08 11:20:38 -07001507 }
1508 }
1509
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001510 private final class InternalRemoveRequestListener
1511 implements ClusterMessageHandler {
1512 @Override
1513 public void handle(ClusterMessage message) {
1514 log.debug("Received device remove request from peer: {}", message.sender());
1515 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001516
Madan Jampani2af244a2015-02-22 13:12:01 -08001517 try {
1518 removeDevice(did);
1519 } catch (Exception e) {
1520 log.warn("Exception thrown handling device remove", e);
1521 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001522 }
1523 }
1524
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001525 private final class InternalDeviceRemovedEventListener
1526 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001527 @Override
1528 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001529 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001530 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001531
1532 DeviceId deviceId = event.deviceId();
1533 Timestamp timestamp = event.timestamp();
1534
Madan Jampani2af244a2015-02-22 13:12:01 -08001535 try {
1536 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1537 } catch (Exception e) {
1538 log.warn("Exception thrown handling device removed", e);
1539 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001540 }
1541 }
1542
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001543 private final class InternalPortEventListener
1544 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001545 @Override
1546 public void handle(ClusterMessage message) {
1547
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001548 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001549 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001550
1551 ProviderId providerId = event.providerId();
1552 DeviceId deviceId = event.deviceId();
1553 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1554
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001555 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001556 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001557 // Note: dropped information will be recovered by anti-entropy
1558 return;
1559 }
1560
Madan Jampani2af244a2015-02-22 13:12:01 -08001561 try {
1562 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1563 } catch (Exception e) {
1564 log.warn("Exception thrown handling port update", e);
1565 }
Madan Jampani47c93732014-10-06 20:46:08 -07001566 }
1567 }
1568
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001569 private final class InternalPortStatusEventListener
1570 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001571 @Override
1572 public void handle(ClusterMessage message) {
1573
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001574 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001575 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001576
1577 ProviderId providerId = event.providerId();
1578 DeviceId deviceId = event.deviceId();
1579 Timestamped<PortDescription> portDescription = event.portDescription();
1580
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001581 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001582 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001583 // Note: dropped information will be recovered by anti-entropy
1584 return;
1585 }
1586
Madan Jampani2af244a2015-02-22 13:12:01 -08001587 try {
1588 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1589 } catch (Exception e) {
1590 log.warn("Exception thrown handling port update", e);
1591 }
Madan Jampani47c93732014-10-06 20:46:08 -07001592 }
1593 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001594
1595 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001596 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001597 @Override
1598 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001599 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001600 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001601 try {
1602 handleAdvertisement(advertisement);
1603 } catch (Exception e) {
1604 log.warn("Exception thrown handling Device advertisements.", e);
1605 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001606 }
1607 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001608
1609 private final class DeviceInjectedEventListener
1610 implements ClusterMessageHandler {
1611 @Override
1612 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001613 log.debug("Received injected device event from peer: {}", message.sender());
1614 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1615
1616 ProviderId providerId = event.providerId();
1617 DeviceId deviceId = event.deviceId();
1618 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001619 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1620 // workaround for ONOS-1208
1621 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1622 return;
1623 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001624
Madan Jampani2af244a2015-02-22 13:12:01 -08001625 try {
1626 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1627 } catch (Exception e) {
1628 log.warn("Exception thrown handling device injected event.", e);
1629 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001630 }
1631 }
1632
1633 private final class PortInjectedEventListener
1634 implements ClusterMessageHandler {
1635 @Override
1636 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001637 log.debug("Received injected port event from peer: {}", message.sender());
1638 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1639
1640 ProviderId providerId = event.providerId();
1641 DeviceId deviceId = event.deviceId();
1642 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001643 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1644 // workaround for ONOS-1208
1645 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1646 return;
1647 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001648
Madan Jampani2af244a2015-02-22 13:12:01 -08001649 try {
1650 updatePorts(providerId, deviceId, portDescriptions);
1651 } catch (Exception e) {
1652 log.warn("Exception thrown handling port injected event.", e);
1653 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001654 }
1655 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001656
1657 private class InternalPortStatsListener
1658 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1659 @Override
1660 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1661 if (event.type() == PUT) {
1662 Device device = devices.get(event.key());
1663 if (device != null) {
1664 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1665 }
1666 }
1667 }
1668 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001669}