blob: 6345643329dfbb610cb6dcf82eb2276a8a611f76 [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);
Dusan Pajin517e2232015-08-24 16:50:11 +0200863 // DeviceEvent returns null because of InternalPortStatsListener usage
864 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200865 }
866
867 /**
868 * Calculate delta statistics by subtracting previous from new statistics.
869 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700870 * @param deviceId device identifier
871 * @param prvStats previous port statistics
872 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200873 * @return PortStatistics
874 */
875 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
876 // calculate time difference
877 long deltaStatsSec, deltaStatsNano;
878 if (newStats.durationNano() < prvStats.durationNano()) {
879 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
880 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
881 } else {
882 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
883 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
884 }
885 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
886 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
887 .setPort(newStats.port())
888 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
889 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
890 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
891 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
892 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
893 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
894 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
895 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
896 .setDurationSec(deltaStatsSec)
897 .setDurationNano(deltaStatsNano)
898 .build();
899 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700900 }
901
902 @Override
903 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700904 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
905 if (portStats == null) {
906 return Collections.emptyList();
907 }
908 return ImmutableList.copyOf(portStats.values());
909 }
910
911 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200912 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
913 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
914 if (portStats == null) {
915 return Collections.emptyList();
916 }
917 return ImmutableList.copyOf(portStats.values());
918 }
919
920 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700921 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
922 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
923 return ports == null ? null : ports.get(portNumber);
924 }
925
926 @Override
927 public boolean isAvailable(DeviceId deviceId) {
928 return availableDevices.contains(deviceId);
929 }
930
931 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700932 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800933 final NodeId myId = clusterService.getLocalNode().id();
934 NodeId master = mastershipService.getMasterFor(deviceId);
935
936 // if there exist a master, forward
937 // if there is no master, try to become one and process
938
939 boolean relinquishAtEnd = false;
940 if (master == null) {
941 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
942 if (myRole != MastershipRole.NONE) {
943 relinquishAtEnd = true;
944 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800945 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800946 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800947 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700948 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800949 master = myId;
950 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700951 }
952
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800953 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800954 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700955 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800956
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800957 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700958 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800959 /* error log:
960 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
961 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800962
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800963 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700964 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800965 }
966
967 // I have control..
968
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700969 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700970 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700971 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800972 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700973 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800974 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700975 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800976 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800977 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800978 mastershipService.relinquishMastership(deviceId);
979 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700980 return event;
981 }
982
983 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
984 Timestamp timestamp) {
985
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700986 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700987 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700988 // accept removal request if given timestamp is newer than
989 // the latest Timestamp from Primary provider
990 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
991 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
992 if (timestamp.compareTo(lastTimestamp) <= 0) {
993 // outdated event ignore
994 return null;
995 }
996 removalRequest.put(deviceId, timestamp);
997
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700998 Device device = devices.remove(deviceId);
999 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001000 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1001 if (ports != null) {
1002 ports.clear();
1003 }
1004 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001005 descs.clear();
1006 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001007 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001008 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001009 }
1010
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001011 /**
1012 * Checks if given timestamp is superseded by removal request
1013 * with more recent timestamp.
1014 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001015 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001016 * @param timestampToCheck timestamp of an event to check
1017 * @return true if device is already removed
1018 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001019 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1020 Timestamp removalTimestamp = removalRequest.get(deviceId);
1021 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001022 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001023 // removalRequest is more recent
1024 return true;
1025 }
1026 return false;
1027 }
1028
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001029 /**
1030 * Returns a Device, merging description given from multiple Providers.
1031 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001032 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001033 * @param providerDescs Collection of Descriptions from multiple providers
1034 * @return Device instance
1035 */
1036 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001037 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001038
Thomas Vachuska444eda62014-10-28 13:09:42 -07001039 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001040
1041 ProviderId primary = pickPrimaryPID(providerDescs);
1042
1043 DeviceDescriptions desc = providerDescs.get(primary);
1044
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001045 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001046 Type type = base.type();
1047 String manufacturer = base.manufacturer();
1048 String hwVersion = base.hwVersion();
1049 String swVersion = base.swVersion();
1050 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001051 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001052 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1053 annotations = merge(annotations, base.annotations());
1054
1055 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1056 if (e.getKey().equals(primary)) {
1057 continue;
1058 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001059 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001060 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001061 // Currently assuming there will never be a key conflict between
1062 // providers
1063
1064 // annotation merging. not so efficient, should revisit later
1065 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1066 }
1067
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001068 return new DefaultDevice(primary, deviceId, type, manufacturer,
1069 hwVersion, swVersion, serialNumber,
1070 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001071 }
1072
Marc De Leenheer88194c32015-05-29 22:10:59 -07001073 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1074 PortDescription description, Annotations annotations) {
1075 switch (description.type()) {
1076 case OMS:
1077 OmsPortDescription omsDesc = (OmsPortDescription) description;
1078 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1079 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1080 case OCH:
1081 OchPortDescription ochDesc = (OchPortDescription) description;
1082 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1083 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1084 case ODUCLT:
1085 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1086 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1087 default:
1088 return new DefaultPort(device, number, isEnabled, description.type(),
1089 description.portSpeed(), annotations);
1090 }
1091 }
1092
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001093 /**
1094 * Returns a Port, merging description given from multiple Providers.
1095 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001096 * @param device device the port is on
1097 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001098 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001099 * @return Port instance
1100 */
1101 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001102 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001103
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001104 ProviderId primary = pickPrimaryPID(descsMap);
1105 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001106 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001107 boolean isEnabled = false;
1108 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001109 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001110 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1111 if (portDesc != null) {
1112 isEnabled = portDesc.value().isEnabled();
1113 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001114 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001115 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001116 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001117 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001118 if (e.getKey().equals(primary)) {
1119 continue;
1120 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001121 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001122 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001123 // Currently assuming there will never be a key conflict between
1124 // providers
1125
1126 // annotation merging. not so efficient, should revisit later
1127 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1128 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001129 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1130 continue;
1131 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001132 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001133 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001134 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001135 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001136 }
1137 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001138 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001139 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001140 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001141 PortDescription current = portDesc.value();
1142 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001143 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001144 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001145 }
1146
1147 /**
1148 * @return primary ProviderID, or randomly chosen one if none exists
1149 */
1150 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001151 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001152 ProviderId fallBackPrimary = null;
1153 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1154 if (!e.getKey().isAncillary()) {
1155 return e.getKey();
1156 } else if (fallBackPrimary == null) {
1157 // pick randomly as a fallback in case there is no primary
1158 fallBackPrimary = e.getKey();
1159 }
1160 }
1161 return fallBackPrimary;
1162 }
1163
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001164 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001165 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001166 ProviderId pid = pickPrimaryPID(providerDescs);
1167 return providerDescs.get(pid);
1168 }
1169
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001170 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001171 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001172 }
1173
Jonathan Hart7d656f42015-01-27 14:07:23 -08001174 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001175 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001176 }
Madan Jampani47c93732014-10-06 20:46:08 -07001177
Jonathan Hart7d656f42015-01-27 14:07:23 -08001178 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001179 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001180 }
1181
Jonathan Hart7d656f42015-01-27 14:07:23 -08001182 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001183 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001184 }
1185
Jonathan Hart7d656f42015-01-27 14:07:23 -08001186 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001187 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001188 }
1189
Jonathan Hart7d656f42015-01-27 14:07:23 -08001190 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001191 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001192 }
1193
Jonathan Hart7d656f42015-01-27 14:07:23 -08001194 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001195 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1196 }
1197
1198 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1199 try {
1200 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1201 } catch (IOException e) {
1202 log.error("Failed to send" + event + " to " + recipient, e);
1203 }
1204 }
1205
1206 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1207 try {
1208 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1209 } catch (IOException e) {
1210 log.error("Failed to send" + event + " to " + recipient, e);
1211 }
1212 }
1213
1214 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1215 try {
1216 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1217 } catch (IOException e) {
1218 log.error("Failed to send" + event + " to " + recipient, e);
1219 }
1220 }
1221
1222 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1223 try {
1224 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1225 } catch (IOException e) {
1226 log.error("Failed to send" + event + " to " + recipient, e);
1227 }
1228 }
1229
1230 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1231 try {
1232 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1233 } catch (IOException e) {
1234 log.error("Failed to send" + event + " to " + recipient, e);
1235 }
1236 }
1237
1238 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1239 final NodeId self = clusterService.getLocalNode().id();
1240
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001241 final int numDevices = deviceDescs.size();
1242 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1243 final int portsPerDevice = 8; // random factor to minimize reallocation
1244 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1245 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001246
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001247 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001248
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001249 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001250 synchronized (devDescs) {
1251
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001252 // send device offline timestamp
1253 Timestamp lOffline = this.offline.get(deviceId);
1254 if (lOffline != null) {
1255 adOffline.put(deviceId, lOffline);
1256 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001257
1258 for (Entry<ProviderId, DeviceDescriptions>
1259 prov : devDescs.entrySet()) {
1260
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001261 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001262 final ProviderId provId = prov.getKey();
1263 final DeviceDescriptions descs = prov.getValue();
1264
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001265 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001266 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001267
1268 for (Entry<PortNumber, Timestamped<PortDescription>>
1269 portDesc : descs.getPortDescs().entrySet()) {
1270
1271 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001272 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001273 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001274 }
1275 }
1276 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001277 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001278
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001279 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001280 }
1281
1282 /**
1283 * Responds to anti-entropy advertisement message.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001284 * <p/>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001285 * Notify sender about out-dated information using regular replication message.
1286 * Send back advertisement to sender if not in sync.
1287 *
1288 * @param advertisement to respond to
1289 */
1290 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1291
1292 final NodeId sender = advertisement.sender();
1293
1294 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1295 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1296 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1297
1298 // Fragments to request
1299 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1300 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1301
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001302 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001303 final DeviceId deviceId = de.getKey();
1304 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1305
1306 synchronized (lDevice) {
1307 // latestTimestamp across provider
1308 // Note: can be null initially
1309 Timestamp localLatest = offline.get(deviceId);
1310
1311 // handle device Ads
1312 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1313 final ProviderId provId = prov.getKey();
1314 final DeviceDescriptions lDeviceDescs = prov.getValue();
1315
1316 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1317
1318
1319 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1320 Timestamp advDevTimestamp = devAds.get(devFragId);
1321
Jonathan Hart403ea932015-02-20 16:23:00 -08001322 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1323 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001324 // remote does not have it or outdated, suggest
1325 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1326 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1327 // local is outdated, request
1328 reqDevices.add(devFragId);
1329 }
1330
1331 // handle port Ads
1332 for (Entry<PortNumber, Timestamped<PortDescription>>
1333 pe : lDeviceDescs.getPortDescs().entrySet()) {
1334
1335 final PortNumber num = pe.getKey();
1336 final Timestamped<PortDescription> lPort = pe.getValue();
1337
1338 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1339
1340 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001341 if (advPortTimestamp == null || lPort.isNewerThan(
1342 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001343 // remote does not have it or outdated, suggest
1344 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1345 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1346 // local is outdated, request
1347 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1348 reqPorts.add(portFragId);
1349 }
1350
1351 // remove port Ad already processed
1352 portAds.remove(portFragId);
1353 } // end local port loop
1354
1355 // remove device Ad already processed
1356 devAds.remove(devFragId);
1357
1358 // find latest and update
1359 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1360 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001361 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001362 localLatest = providerLatest;
1363 }
1364 } // end local provider loop
1365
1366 // checking if remote timestamp is more recent.
1367 Timestamp rOffline = offlineAds.get(deviceId);
1368 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001369 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001370 // remote offline timestamp suggests that the
1371 // device is off-line
1372 markOfflineInternal(deviceId, rOffline);
1373 }
1374
1375 Timestamp lOffline = offline.get(deviceId);
1376 if (lOffline != null && rOffline == null) {
1377 // locally offline, but remote is online, suggest offline
1378 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1379 }
1380
1381 // remove device offline Ad already processed
1382 offlineAds.remove(deviceId);
1383 } // end local device loop
1384 } // device lock
1385
1386 // If there is any Ads left, request them
1387 log.trace("Ads left {}, {}", devAds, portAds);
1388 reqDevices.addAll(devAds.keySet());
1389 reqPorts.addAll(portAds.keySet());
1390
1391 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1392 log.trace("Nothing to request to remote peer {}", sender);
1393 return;
1394 }
1395
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001396 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001397
1398 // 2-way Anti-Entropy for now
1399 try {
1400 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1401 } catch (IOException e) {
1402 log.error("Failed to send response advertisement to " + sender, e);
1403 }
1404
1405// Sketch of 3-way Anti-Entropy
1406// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1407// ClusterMessage message = new ClusterMessage(
1408// clusterService.getLocalNode().id(),
1409// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1410// SERIALIZER.encode(request));
1411//
1412// try {
1413// clusterCommunicator.unicast(message, advertisement.sender());
1414// } catch (IOException e) {
1415// log.error("Failed to send advertisement reply to "
1416// + advertisement.sender(), e);
1417// }
Madan Jampani47c93732014-10-06 20:46:08 -07001418 }
1419
Madan Jampani255a58b2014-10-09 12:08:20 -07001420 private void notifyDelegateIfNotNull(DeviceEvent event) {
1421 if (event != null) {
1422 notifyDelegate(event);
1423 }
1424 }
1425
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001426 private final class SendAdvertisementTask implements Runnable {
1427
1428 @Override
1429 public void run() {
1430 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001431 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001432 return;
1433 }
1434
1435 try {
1436 final NodeId self = clusterService.getLocalNode().id();
1437 Set<ControllerNode> nodes = clusterService.getNodes();
1438
1439 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1440 .transform(toNodeId())
1441 .toList();
1442
1443 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001444 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001445 return;
1446 }
1447
1448 NodeId peer;
1449 do {
1450 int idx = RandomUtils.nextInt(0, nodeIds.size());
1451 peer = nodeIds.get(idx);
1452 } while (peer.equals(self));
1453
1454 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1455
1456 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001457 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001458 return;
1459 }
1460
1461 try {
1462 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1463 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001464 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001465 return;
1466 }
1467 } catch (Exception e) {
1468 // catch all Exception to avoid Scheduled task being suppressed.
1469 log.error("Exception thrown while sending advertisement", e);
1470 }
1471 }
1472 }
1473
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001474 private final class InternalDeviceEventListener
1475 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001476 @Override
1477 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001478 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001479 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001480
Madan Jampani47c93732014-10-06 20:46:08 -07001481 ProviderId providerId = event.providerId();
1482 DeviceId deviceId = event.deviceId();
1483 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001484
Madan Jampani2af244a2015-02-22 13:12:01 -08001485 try {
1486 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1487 } catch (Exception e) {
1488 log.warn("Exception thrown handling device update", e);
1489 }
Madan Jampani47c93732014-10-06 20:46:08 -07001490 }
1491 }
1492
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001493 private final class InternalDeviceOfflineEventListener
1494 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001495 @Override
1496 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001497 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001498 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001499
1500 DeviceId deviceId = event.deviceId();
1501 Timestamp timestamp = event.timestamp();
1502
Madan Jampani2af244a2015-02-22 13:12:01 -08001503 try {
1504 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1505 } catch (Exception e) {
1506 log.warn("Exception thrown handling device offline", e);
1507 }
Madan Jampani25322532014-10-08 11:20:38 -07001508 }
1509 }
1510
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001511 private final class InternalRemoveRequestListener
1512 implements ClusterMessageHandler {
1513 @Override
1514 public void handle(ClusterMessage message) {
1515 log.debug("Received device remove request from peer: {}", message.sender());
1516 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001517
Madan Jampani2af244a2015-02-22 13:12:01 -08001518 try {
1519 removeDevice(did);
1520 } catch (Exception e) {
1521 log.warn("Exception thrown handling device remove", e);
1522 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001523 }
1524 }
1525
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001526 private final class InternalDeviceRemovedEventListener
1527 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001528 @Override
1529 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001530 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001531 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001532
1533 DeviceId deviceId = event.deviceId();
1534 Timestamp timestamp = event.timestamp();
1535
Madan Jampani2af244a2015-02-22 13:12:01 -08001536 try {
1537 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1538 } catch (Exception e) {
1539 log.warn("Exception thrown handling device removed", e);
1540 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001541 }
1542 }
1543
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001544 private final class InternalPortEventListener
1545 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001546 @Override
1547 public void handle(ClusterMessage message) {
1548
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001549 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001550 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001551
1552 ProviderId providerId = event.providerId();
1553 DeviceId deviceId = event.deviceId();
1554 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1555
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001556 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001557 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001558 // Note: dropped information will be recovered by anti-entropy
1559 return;
1560 }
1561
Madan Jampani2af244a2015-02-22 13:12:01 -08001562 try {
1563 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1564 } catch (Exception e) {
1565 log.warn("Exception thrown handling port update", e);
1566 }
Madan Jampani47c93732014-10-06 20:46:08 -07001567 }
1568 }
1569
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001570 private final class InternalPortStatusEventListener
1571 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001572 @Override
1573 public void handle(ClusterMessage message) {
1574
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001575 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001576 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001577
1578 ProviderId providerId = event.providerId();
1579 DeviceId deviceId = event.deviceId();
1580 Timestamped<PortDescription> portDescription = event.portDescription();
1581
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001582 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001583 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001584 // Note: dropped information will be recovered by anti-entropy
1585 return;
1586 }
1587
Madan Jampani2af244a2015-02-22 13:12:01 -08001588 try {
1589 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1590 } catch (Exception e) {
1591 log.warn("Exception thrown handling port update", e);
1592 }
Madan Jampani47c93732014-10-06 20:46:08 -07001593 }
1594 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001595
1596 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001597 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001598 @Override
1599 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001600 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001601 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001602 try {
1603 handleAdvertisement(advertisement);
1604 } catch (Exception e) {
1605 log.warn("Exception thrown handling Device advertisements.", e);
1606 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001607 }
1608 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001609
1610 private final class DeviceInjectedEventListener
1611 implements ClusterMessageHandler {
1612 @Override
1613 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001614 log.debug("Received injected device event from peer: {}", message.sender());
1615 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1616
1617 ProviderId providerId = event.providerId();
1618 DeviceId deviceId = event.deviceId();
1619 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001620 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1621 // workaround for ONOS-1208
1622 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1623 return;
1624 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001625
Madan Jampani2af244a2015-02-22 13:12:01 -08001626 try {
1627 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1628 } catch (Exception e) {
1629 log.warn("Exception thrown handling device injected event.", e);
1630 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001631 }
1632 }
1633
1634 private final class PortInjectedEventListener
1635 implements ClusterMessageHandler {
1636 @Override
1637 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001638 log.debug("Received injected port event from peer: {}", message.sender());
1639 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1640
1641 ProviderId providerId = event.providerId();
1642 DeviceId deviceId = event.deviceId();
1643 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001644 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1645 // workaround for ONOS-1208
1646 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1647 return;
1648 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001649
Madan Jampani2af244a2015-02-22 13:12:01 -08001650 try {
1651 updatePorts(providerId, deviceId, portDescriptions);
1652 } catch (Exception e) {
1653 log.warn("Exception thrown handling port injected event.", e);
1654 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001655 }
1656 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001657
1658 private class InternalPortStatsListener
1659 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1660 @Override
1661 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1662 if (event.type() == PUT) {
1663 Device device = devices.get(event.key());
1664 if (device != null) {
1665 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1666 }
1667 }
1668 }
1669 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001670}