blob: ea7ebd3bba3450e1057bb0137b1f5916a78b6d4b [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2014-present Open Networking Foundation
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
Ray Milkey2bf5ea72017-06-01 09:03:34 -070018import java.io.IOException;
19import java.util.ArrayList;
20import java.util.Collection;
21import java.util.Collections;
22import java.util.HashMap;
23import java.util.HashSet;
24import java.util.Iterator;
25import java.util.List;
26import java.util.Map;
27import java.util.Map.Entry;
28import java.util.Objects;
29import java.util.Optional;
30import java.util.Set;
31import java.util.concurrent.ConcurrentHashMap;
32import java.util.concurrent.ConcurrentMap;
33import java.util.concurrent.ExecutorService;
34import java.util.concurrent.ScheduledExecutorService;
35import java.util.concurrent.TimeUnit;
36import java.util.function.Consumer;
37import java.util.stream.Stream;
38
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070039import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070040import org.apache.felix.scr.annotations.Activate;
41import org.apache.felix.scr.annotations.Component;
42import org.apache.felix.scr.annotations.Deactivate;
43import org.apache.felix.scr.annotations.Reference;
44import org.apache.felix.scr.annotations.ReferenceCardinality;
45import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080046import org.onlab.packet.ChassisId;
47import org.onlab.util.KryoNamespace;
Brian O'Connorabafb502014-12-02 22:26:20 -080048import org.onosproject.cluster.ClusterService;
49import org.onosproject.cluster.ControllerNode;
50import org.onosproject.cluster.NodeId;
51import org.onosproject.mastership.MastershipService;
Brian O'Connorabafb502014-12-02 22:26:20 -080052import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070053import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080054import org.onosproject.net.AnnotationsUtil;
55import org.onosproject.net.DefaultAnnotations;
56import org.onosproject.net.DefaultDevice;
57import org.onosproject.net.DefaultPort;
58import org.onosproject.net.Device;
59import org.onosproject.net.Device.Type;
60import org.onosproject.net.DeviceId;
61import org.onosproject.net.MastershipRole;
62import org.onosproject.net.Port;
63import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070064import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080065import org.onosproject.net.device.DeviceClockService;
66import org.onosproject.net.device.DeviceDescription;
67import org.onosproject.net.device.DeviceEvent;
68import org.onosproject.net.device.DeviceStore;
69import org.onosproject.net.device.DeviceStoreDelegate;
70import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070071import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080072import org.onosproject.net.provider.ProviderId;
73import org.onosproject.store.AbstractStore;
74import org.onosproject.store.Timestamp;
75import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
Brian O'Connorabafb502014-12-02 22:26:20 -080076import org.onosproject.store.cluster.messaging.MessageSubject;
Jordan Haltermanebedbb52017-08-08 15:57:50 -070077import org.onosproject.store.impl.MastershipBasedTimestamp;
Brian O'Connorabafb502014-12-02 22:26:20 -080078import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070079import org.onosproject.store.serializers.KryoNamespaces;
Brian O'Connor6de2e202015-05-21 14:30:41 -070080import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070081import org.onosproject.store.service.EventuallyConsistentMap;
82import org.onosproject.store.service.EventuallyConsistentMapEvent;
83import org.onosproject.store.service.EventuallyConsistentMapListener;
84import org.onosproject.store.service.MultiValuedTimestamp;
Jordan Halterman2c83a102017-08-20 17:11:41 -070085import org.onosproject.store.service.Serializer;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070086import org.onosproject.store.service.StorageService;
87import org.onosproject.store.service.WallClockTimestamp;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070088import org.slf4j.Logger;
89
Ray Milkey2bf5ea72017-06-01 09:03:34 -070090import com.google.common.collect.FluentIterable;
91import com.google.common.collect.ImmutableList;
92import com.google.common.collect.Maps;
93import com.google.common.collect.Sets;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070094
95import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070096import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070097import static com.google.common.base.Verify.verify;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -080098import static java.util.concurrent.Executors.newCachedThreadPool;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080099import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800100import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800101import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800102import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
Ray Milkey9ef22232016-07-14 12:42:37 -0700103import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED;
104import static org.onosproject.net.device.DeviceEvent.Type.PORT_ADDED;
105import static org.onosproject.net.device.DeviceEvent.Type.PORT_REMOVED;
106import static org.onosproject.net.device.DeviceEvent.Type.PORT_STATS_UPDATED;
107import static org.onosproject.net.device.DeviceEvent.Type.PORT_UPDATED;
108import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700109import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE;
110import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVED;
Ray Milkey9ef22232016-07-14 12:42:37 -0700111import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700112import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_UPDATE;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700113import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE;
114import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_UPDATE;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700115import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800116import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700117
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700118/**
119 * Manages inventory of infrastructure devices using gossip protocol to distribute
120 * information.
121 */
122@Component(immediate = true)
123@Service
124public class GossipDeviceStore
125 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
126 implements DeviceStore {
127
128 private final Logger log = getLogger(getClass());
129
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700130 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800131 // Timeout in milliseconds to process device or ports on remote master node
132 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700133
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700134 // innerMap is used to lock a Device, thus instance should never be replaced.
135 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700136 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700137 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700138
139 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700140 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
141 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700142
143 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200144 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700145 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
146 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700147
148 // to be updated under Device lock
149 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
150 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700151
152 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700153 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700154
155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700156 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700157
Madan Jampani47c93732014-10-06 20:46:08 -0700158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700159 protected StorageService storageService;
160
161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700162 protected ClusterCommunicationService clusterCommunicator;
163
Madan Jampani53e44e62014-10-07 12:39:51 -0700164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
165 protected ClusterService clusterService;
166
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
168 protected MastershipService mastershipService;
169
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800170 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
171 protected MastershipTermService termService;
172
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700173 private static final Timestamp DEFAULT_TIMESTAMP = new MastershipBasedTimestamp(0, 0);
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800174
Jordan Halterman2c83a102017-08-20 17:11:41 -0700175 protected static final Serializer SERIALIZER = Serializer.using(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)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700186 .build("GossipDevice"));
Madan Jampani53e44e62014-10-07 12:39:51 -0700187
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800188 private ExecutorService executor;
189
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800190 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700191
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800192 // TODO make these anti-entropy parameters configurable
193 private long initialDelaySec = 5;
194 private long periodSec = 5;
195
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700196 @Activate
197 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800198 executor = newCachedThreadPool(groupedThreads("onos/device", "fg-%d", log));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800199
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800200 backgroundExecutor =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800201 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d", log)));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700202
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700203 addSubscriber(DEVICE_UPDATE, this::handleDeviceEvent);
204 addSubscriber(DEVICE_OFFLINE, this::handleDeviceOfflineEvent);
205 addSubscriber(DEVICE_REMOVE_REQ, this::handleRemoveRequest);
206 addSubscriber(DEVICE_REMOVED, this::handleDeviceRemovedEvent);
207 addSubscriber(PORT_UPDATE, this::handlePortEvent);
208 addSubscriber(PORT_STATUS_UPDATE, this::handlePortStatusEvent);
209 addSubscriber(DEVICE_ADVERTISE, this::handleDeviceAdvertisement);
Madan Jampani2af244a2015-02-22 13:12:01 -0800210
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700211 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800212 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700213 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700214
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700215 // Create a distributed map for port stats.
216 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
217 .register(KryoNamespaces.API)
HIGUCHI Yuta03666a32016-05-18 11:49:09 -0700218 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
219 .register(MultiValuedTimestamp.class);
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700220
221 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
222 .withName("port-stats")
223 .withSerializer(deviceDataSerializer)
224 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700225 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700226 .withTombstonesDisabled()
227 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200228 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
229 eventuallyConsistentMapBuilder()
230 .withName("port-stats-delta")
231 .withSerializer(deviceDataSerializer)
232 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
233 .withTimestampProvider((k, v) -> new WallClockTimestamp())
234 .withTombstonesDisabled()
235 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700236 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700237 log.info("Started");
238 }
239
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700240 private <M> void addSubscriber(MessageSubject subject, Consumer<M> handler) {
241 clusterCommunicator.addSubscriber(subject, SERIALIZER::decode, handler, executor);
242 }
243
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700244 @Deactivate
245 public void deactivate() {
Frank Wange0eb5ce2016-07-01 18:21:25 +0800246 devicePortStats.removeListener(portStatsListener);
Madan Jampani632f16b2015-08-11 12:42:59 -0700247 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200248 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800249 executor.shutdownNow();
250
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800251 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700252 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800253 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700254 log.error("Timeout during executor shutdown");
255 }
256 } catch (InterruptedException e) {
257 log.error("Error during executor shutdown", e);
258 }
259
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700260 deviceDescs.clear();
261 devices.clear();
262 devicePorts.clear();
263 availableDevices.clear();
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700264 clusterCommunicator.removeSubscriber(DEVICE_UPDATE);
265 clusterCommunicator.removeSubscriber(DEVICE_OFFLINE);
266 clusterCommunicator.removeSubscriber(DEVICE_REMOVE_REQ);
267 clusterCommunicator.removeSubscriber(DEVICE_REMOVED);
268 clusterCommunicator.removeSubscriber(PORT_UPDATE);
269 clusterCommunicator.removeSubscriber(PORT_STATUS_UPDATE);
270 clusterCommunicator.removeSubscriber(DEVICE_ADVERTISE);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700271 log.info("Stopped");
272 }
273
274 @Override
275 public int getDeviceCount() {
276 return devices.size();
277 }
278
279 @Override
mskala0d0c6832017-07-12 11:21:23 +0200280 public int getAvailableDeviceCount() {
281 return availableDevices.size();
282 }
283
284 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700285 public Iterable<Device> getDevices() {
286 return Collections.unmodifiableCollection(devices.values());
287 }
288
289 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800290 public Iterable<Device> getAvailableDevices() {
291 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700292 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800293 }
294
295 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700296 public Device getDevice(DeviceId deviceId) {
297 return devices.get(deviceId);
298 }
299
300 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700301 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700302 DeviceId deviceId,
303 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800304 NodeId localNode = clusterService.getLocalNode().id();
305 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Jordan Haltermanf9f55632017-12-19 14:56:08 -0800306 boolean isMaster = localNode.equals(deviceNode);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800307
308 // Process device update only if we're the master,
309 // otherwise signal the actual master.
310 DeviceEvent deviceEvent = null;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800311
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700312 // If this node is the master for the device, acquire a new timestamp. Otherwise,
313 // use a 0,0 or tombstone timestamp to create the device if it doesn't already exist.
Jordan Haltermanf9f55632017-12-19 14:56:08 -0800314 Timestamp newTimestamp;
315 try {
316 newTimestamp = isMaster
317 ? deviceClockService.getTimestamp(deviceId)
318 : removalRequest.getOrDefault(deviceId, DEFAULT_TIMESTAMP);
319 } catch (IllegalStateException e) {
320 newTimestamp = removalRequest.getOrDefault(deviceDescription, DEFAULT_TIMESTAMP);
321 isMaster = false;
322 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700323 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
324 final Timestamped<DeviceDescription> mergedDesc;
325 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800326
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700327 synchronized (device) {
328 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
Jordan Halterman8a0b3972017-08-15 16:14:18 -0700329 if (deviceEvent == null) {
330 return null;
331 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700332 mergedDesc = device.get(providerId).getDeviceDesc();
333 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800334
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700335 // If this node is the master for the device, update peers.
336 if (isMaster) {
Jordan Halterman8a0b3972017-08-15 16:14:18 -0700337 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
338 providerId, deviceId);
339 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700340 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800341
342 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700343 }
344
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700345 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700346 DeviceId deviceId,
347 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700348
349 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800350 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700351 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700352
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800353 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700354 // locking per device
355
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700356 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
357 log.debug("Ignoring outdated event: {}", deltaDesc);
358 return null;
359 }
360
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800361 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700362
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700363 final Device oldDevice = devices.get(deviceId);
364 final Device newDevice;
365
366 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700367 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700368 // on new device or valid update
369 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800370 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700371 } else {
372 // outdated event, ignored.
373 return null;
374 }
375 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700376 // REGISTER
377 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700378 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700379 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700380 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700381 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700382 } else {
383 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700384 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
385 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700386 }
387 }
388 }
389
390 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700391 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700392 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700393 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700394
395 // update composed device cache
396 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
397 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700398 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
399 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700400
401 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700402 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700403 }
404
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700405 log.debug("Device {} added", newDevice.id());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700406 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
407 }
408
409 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700410 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700411 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700412 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700413 Device newDevice, Timestamp newTimestamp,
414 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700415 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700416 boolean propertiesChanged =
417 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700418 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
mskala4b2081a2017-06-12 16:39:50 +0200419 !Objects.equals(oldDevice.providerId(), newDevice.providerId()) ||
420 !Objects.equals(oldDevice.chassisId(), newDevice.chassisId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700421 boolean annotationsChanged =
422 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700423
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700424 // Primary providers can respond to all changes, but ancillary ones
425 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800426 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700427 if ((providerId.isAncillary() && annotationsChanged) ||
428 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700429 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
430 if (!replaced) {
431 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700432 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800433 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700434 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700435
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700436 log.debug("Device {} updated", newDevice.id());
alshabibdc5d8bd2015-11-02 15:41:29 -0800437 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700438 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800439
helenyrwufd296b62016-06-22 17:43:02 -0700440 if (!providerId.isAncillary() && forceAvailable) {
alshabibdc5d8bd2015-11-02 15:41:29 -0800441 boolean wasOnline = availableDevices.contains(newDevice.id());
442 markOnline(newDevice.id(), newTimestamp);
443 if (!wasOnline) {
444 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
445 }
446 }
447 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700448 }
449
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700450 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700451 // update composed device cache
452 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
453 verify(oldDevice == null,
454 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
455 providerId, oldDevice, newDevice);
456
457 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700458 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700459 }
460
461 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
462 }
463
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700464 @Override
465 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700466 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
467 }
468
469 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700470 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700471 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700472 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700473 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800474 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700475 }
476 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700477 }
478
479 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700480 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700481 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700482
483 // locking device
484 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700485 // accept off-line if given timestamp is newer than
486 // the latest Timestamp from Primary provider
487 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
Thomas Vachuska4bd10b92016-12-15 10:13:38 -0800488 if (primDescs == null) {
489 return null;
490 }
491
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700492 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Saritha781984f2017-06-27 09:46:02 +0530493 if (lastTimestamp == null) {
494 lastTimestamp = deviceClockService.getTimestamp(deviceId);
495 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700496 if (timestamp.compareTo(lastTimestamp) <= 0) {
497 // outdated event ignore
498 return null;
499 }
500
501 offline.put(deviceId, timestamp);
502
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700503 Device device = devices.get(deviceId);
504 if (device == null) {
505 return null;
506 }
507 boolean removed = availableDevices.remove(deviceId);
508 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700509 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700510 }
511 return null;
512 }
513 }
514
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700515 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700516 public boolean markOnline(DeviceId deviceId) {
517 if (devices.containsKey(deviceId)) {
518 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
519 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
520 synchronized (deviceLock) {
521 if (markOnline(deviceId, timestamp)) {
522 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
523 return true;
524 } else {
525 return false;
526 }
527 }
528 }
529 log.warn("Device {} does not exist in store", deviceId);
530 return false;
531
532 }
533
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700534 /**
535 * Marks the device as available if the given timestamp is not outdated,
536 * compared to the time the device has been marked offline.
537 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700538 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700539 * @param timestamp of the event triggering this change.
540 * @return true if availability change request was accepted and changed the state
541 */
542 // Guarded by deviceDescs value (=Device lock)
543 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
544 // accept on-line if given timestamp is newer than
545 // the latest offline request Timestamp
546 Timestamp offlineTimestamp = offline.get(deviceId);
547 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700548 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700549
550 offline.remove(deviceId);
551 return availableDevices.add(deviceId);
552 }
553 return false;
554 }
555
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700556 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700557 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700558 DeviceId deviceId,
559 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700560
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800561 NodeId localNode = clusterService.getLocalNode().id();
562 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
563 // since it will trigger distributed store read.
564 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
565 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
566 // If we don't care much about topology performance, then it might be OK.
567 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700568
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800569 // Process port update only if we're the master of the device,
570 // otherwise signal the actual master.
571 List<DeviceEvent> deviceEvents = null;
572 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700573
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800574 final Timestamp newTimestamp;
575 try {
576 newTimestamp = deviceClockService.getTimestamp(deviceId);
577 } catch (IllegalStateException e) {
578 log.info("Timestamp was not available for device {}", deviceId);
579 log.debug(" discarding {}", portDescriptions);
580 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700581
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800582 // Possible situation:
583 // Device connected and became master for short period of time,
584 // but lost mastership before this instance had the chance to
585 // retrieve term information.
586
587 // Information dropped here is expected to be recoverable by
588 // device probing after mastership change
589
590 return Collections.emptyList();
591 }
592 log.debug("timestamp for {} {}", deviceId, newTimestamp);
593
594 final Timestamped<List<PortDescription>> timestampedInput
595 = new Timestamped<>(portDescriptions, newTimestamp);
596 final Timestamped<List<PortDescription>> merged;
597
598 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
599
600 synchronized (device) {
601 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
602 final DeviceDescriptions descs = device.get(providerId);
603 List<PortDescription> mergedList =
604 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700605 .transform(input ->
606 // lookup merged port description
607 descs.getPortDesc(input.portNumber()).value()
608 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700609 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800610 }
611
612 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700613 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700614 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800615 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
616 }
617
618 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700619 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700620 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700621
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800622 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700623 }
624
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700625 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700626 DeviceId deviceId,
627 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700628
629 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700630 if (device == null) {
631 log.debug("Device is no longer valid: {}", deviceId);
632 return Collections.emptyList();
633 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700634
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700635 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700636 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
637
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700638 List<DeviceEvent> events = new ArrayList<>();
639 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700640
641 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
642 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700643 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700644 }
645
646 DeviceDescriptions descs = descsMap.get(providerId);
647 // every provider must provide DeviceDescription.
648 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700649 "Device description for Device ID %s from Provider %s was not found",
650 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700651
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700652 Map<PortNumber, Port> ports = getPortMap(deviceId);
653
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700654 final Timestamp newTimestamp = portDescriptions.timestamp();
655
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700656 // Add new ports
657 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700658 for (PortDescription portDescription : portDescriptions.value()) {
659 final PortNumber number = portDescription.portNumber();
660 processed.add(number);
661
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700662 final Port oldPort = ports.get(number);
663 final Port newPort;
664
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700665
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700666 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
667 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700668 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700669 // on new port or valid update
670 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700671 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700672 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700673 newPort = composePort(device, number, descsMap);
674 } else {
675 // outdated event, ignored.
676 continue;
677 }
678
679 events.add(oldPort == null ?
680 createPort(device, newPort, ports) :
681 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700682 }
683
684 events.addAll(pruneOldPorts(device, ports, processed));
685 }
686 return FluentIterable.from(events).filter(notNull()).toList();
687 }
688
689 // Creates a new port based on the port description adds it to the map and
690 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700691 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700692 private DeviceEvent createPort(Device device, Port newPort,
693 Map<PortNumber, Port> ports) {
694 ports.put(newPort.number(), newPort);
695 return new DeviceEvent(PORT_ADDED, device, newPort);
696 }
697
698 // Checks if the specified port requires update and if so, it replaces the
699 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700700 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700701 private DeviceEvent updatePort(Device device, Port oldPort,
702 Port newPort,
703 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100704
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700705 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700706 oldPort.type() != newPort.type() ||
707 oldPort.portSpeed() != newPort.portSpeed() ||
708 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700709 ports.put(oldPort.number(), newPort);
710 return new DeviceEvent(PORT_UPDATED, device, newPort);
711 }
712 return null;
713 }
714
Michal Machce774332017-01-25 11:02:55 +0100715 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
716
717 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
718 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
719
720 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
721 }
722
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700723 // Prunes the specified list of ports based on which ports are in the
724 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700725 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700726 private List<DeviceEvent> pruneOldPorts(Device device,
727 Map<PortNumber, Port> ports,
728 Set<PortNumber> processed) {
729 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700730 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700731 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700732 Entry<PortNumber, Port> e = iterator.next();
733 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700734 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700735 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700736 iterator.remove();
737 }
738 }
739 return events;
740 }
741
742 // Gets the map of ports for the specified device; if one does not already
743 // exist, it creates and registers a new one.
744 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700745 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700746 }
747
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700748 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700749 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700750 Map<ProviderId, DeviceDescriptions> r;
751 r = deviceDescs.get(deviceId);
752 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700753 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700754 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
755 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
756 if (concurrentlyAdded != null) {
757 r = concurrentlyAdded;
758 }
759 }
760 return r;
761 }
762
763 // Guarded by deviceDescs value (=Device lock)
764 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
765 Map<ProviderId, DeviceDescriptions> device,
766 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700767 synchronized (device) {
768 DeviceDescriptions r = device.get(providerId);
769 if (r == null) {
770 r = new DeviceDescriptions(deltaDesc);
771 device.put(providerId, r);
772 }
773 return r;
774 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700775 }
776
777 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700778 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
779 DeviceId deviceId,
780 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700781 final Timestamp newTimestamp;
782 try {
783 newTimestamp = deviceClockService.getTimestamp(deviceId);
784 } catch (IllegalStateException e) {
785 log.info("Timestamp was not available for device {}", deviceId);
786 log.debug(" discarding {}", portDescription);
787 // Failed to generate timestamp. Ignoring.
788 // See updatePorts comment
789 return null;
790 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700791 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700792 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700793 final DeviceEvent event;
794 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800795 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
796 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700797 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800798 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700799 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700800 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700801 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700802 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700803 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800804 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700805 }
806 return event;
807 }
808
809 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700810 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700811 Device device = devices.get(deviceId);
812 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
813
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700814 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700815 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
816
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700817 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700818
819 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
820 log.debug("Ignoring outdated event: {}", deltaDesc);
821 return null;
822 }
823
824 DeviceDescriptions descs = descsMap.get(providerId);
825 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700826 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700827 "Device description for Device ID %s from Provider %s was not found",
828 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700829
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700830 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
831 final PortNumber number = deltaDesc.value().portNumber();
832 final Port oldPort = ports.get(number);
833 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700834 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100835 boolean toDelete = false;
836
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700837 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700838 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700839 // on new port or valid update
840 // update description
841 descs.putPortDesc(deltaDesc);
842 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100843 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700844 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700845 // same or outdated event, ignored.
846 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700847 return null;
848 }
849
850 if (oldPort == null) {
851 return createPort(device, newPort, ports);
852 } else {
Michal Machce774332017-01-25 11:02:55 +0100853 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700854 }
855 }
856 }
857
858 @Override
859 public List<Port> getPorts(DeviceId deviceId) {
860 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
861 if (ports == null) {
862 return Collections.emptyList();
863 }
864 return ImmutableList.copyOf(ports.values());
865 }
866
867 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700868 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
869 DeviceId deviceId) {
870 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
871 if (descs == null) {
872 return null;
873 }
874 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
875 final Optional<DeviceDescriptions> devDescs;
876 synchronized (descs) {
877 devDescs = Optional.ofNullable(descs.get(pid));
878 }
879 // DeviceDescriptions is concurrent access-safe
880 return devDescs
881 .map(dd -> dd.getPortDescs().values().stream()
882 .map(Timestamped::value))
883 .orElse(Stream.empty());
884 }
885
886 @Override
sangho538108b2015-04-08 14:29:20 -0700887 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200888 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700889
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200890 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
891 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
892 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
893
894 if (prvStatsMap != null) {
895 for (PortStatistics newStats : newStatsCollection) {
896 PortNumber port = PortNumber.portNumber(newStats.port());
897 PortStatistics prvStats = prvStatsMap.get(port);
898 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
899 PortStatistics deltaStats = builder.build();
900 if (prvStats != null) {
901 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
902 }
903 deltaStatsMap.put(port, deltaStats);
904 newStatsMap.put(port, newStats);
905 }
906 } else {
907 for (PortStatistics newStats : newStatsCollection) {
908 PortNumber port = PortNumber.portNumber(newStats.port());
909 newStatsMap.put(port, newStats);
910 }
sangho538108b2015-04-08 14:29:20 -0700911 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200912 devicePortDeltaStats.put(deviceId, deltaStatsMap);
913 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200914 // DeviceEvent returns null because of InternalPortStatsListener usage
915 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200916 }
917
918 /**
919 * Calculate delta statistics by subtracting previous from new statistics.
920 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700921 * @param deviceId device identifier
922 * @param prvStats previous port statistics
923 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200924 * @return PortStatistics
925 */
926 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
927 // calculate time difference
928 long deltaStatsSec, deltaStatsNano;
929 if (newStats.durationNano() < prvStats.durationNano()) {
930 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
931 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
932 } else {
933 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
934 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
935 }
936 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
937 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
938 .setPort(newStats.port())
939 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
940 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
941 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
942 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
943 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
944 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
945 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
946 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
947 .setDurationSec(deltaStatsSec)
948 .setDurationNano(deltaStatsNano)
949 .build();
950 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700951 }
952
953 @Override
954 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700955 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
956 if (portStats == null) {
957 return Collections.emptyList();
958 }
959 return ImmutableList.copyOf(portStats.values());
960 }
961
962 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530963 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
964 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
965 if (portStatsMap == null) {
966 return null;
967 }
968 PortStatistics portStats = portStatsMap.get(portNumber);
969 return portStats;
970 }
971
972 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200973 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
974 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
975 if (portStats == null) {
976 return Collections.emptyList();
977 }
978 return ImmutableList.copyOf(portStats.values());
979 }
980
981 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530982 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
983 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
984 if (portStatsMap == null) {
985 return null;
986 }
987 PortStatistics portStats = portStatsMap.get(portNumber);
988 return portStats;
989 }
990
991 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700992 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
993 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
994 return ports == null ? null : ports.get(portNumber);
995 }
996
997 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700998 public PortDescription getPortDescription(ProviderId pid,
999 DeviceId deviceId,
1000 PortNumber portNumber) {
1001 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1002 if (descs == null) {
1003 return null;
1004 }
1005 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1006 final Optional<DeviceDescriptions> devDescs;
1007 synchronized (descs) {
1008 devDescs = Optional.ofNullable(descs.get(pid));
1009 }
1010 // DeviceDescriptions is concurrent access-safe
1011 return devDescs
1012 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1013 .map(Timestamped::value)
1014 .orElse(null);
1015 }
1016
1017 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001018 public boolean isAvailable(DeviceId deviceId) {
1019 return availableDevices.contains(deviceId);
1020 }
1021
1022 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001023 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001024 final NodeId myId = clusterService.getLocalNode().id();
1025 NodeId master = mastershipService.getMasterFor(deviceId);
1026
1027 // if there exist a master, forward
1028 // if there is no master, try to become one and process
1029
1030 boolean relinquishAtEnd = false;
1031 if (master == null) {
1032 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1033 if (myRole != MastershipRole.NONE) {
1034 relinquishAtEnd = true;
1035 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001036 log.debug("Temporarily requesting role for {} to remove", deviceId);
Jordan Haltermanf1c602d2017-10-18 11:26:52 -07001037 if (mastershipService.requestRoleFor(deviceId).join() == MastershipRole.MASTER) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001038 master = myId;
1039 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001040 }
1041
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001042 boolean isMaster = myId.equals(master);
1043
1044 // If this node is not the master, forward the request.
1045 if (!isMaster) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001046 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001047 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001048
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001049 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001050 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001051 /* error log:
1052 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1053 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001054 }
1055
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001056 // If this node is the master, get a timestamp. Otherwise, default to the current device timestamp.
1057 Timestamp timestamp = isMaster ? deviceClockService.getTimestamp(deviceId) : null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001058
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001059 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001060
1061 // If this node is the master, update peers.
1062 if (isMaster && event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001063 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001064 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001065 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001066 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001067
1068 // Relinquish mastership if acquired to remove the device.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001069 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001070 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001071 mastershipService.relinquishMastership(deviceId);
1072 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001073 return event;
1074 }
1075
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001076 private DeviceEvent removeDeviceInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001077
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001078 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001079 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001080 // accept removal request if given timestamp is newer than
1081 // the latest Timestamp from Primary provider
1082 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001083 if (primDescs == null) {
1084 return null;
1085 }
1086
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001087 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001088
1089 // If no timestamp is set, default the timestamp to the last timestamp for the device.
1090 if (timestamp == null) {
1091 timestamp = lastTimestamp;
1092 }
1093
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001094 if (timestamp.compareTo(lastTimestamp) <= 0) {
1095 // outdated event ignore
1096 return null;
1097 }
1098 removalRequest.put(deviceId, timestamp);
1099
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001100 Device device = devices.remove(deviceId);
1101 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001102 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1103 if (ports != null) {
1104 ports.clear();
1105 }
1106 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001107 descs.clear();
1108 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001109 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001110 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001111 }
1112
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001113 /**
1114 * Checks if given timestamp is superseded by removal request
1115 * with more recent timestamp.
1116 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001117 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001118 * @param timestampToCheck timestamp of an event to check
1119 * @return true if device is already removed
1120 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001121 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1122 Timestamp removalTimestamp = removalRequest.get(deviceId);
1123 if (removalTimestamp != null &&
Jordan Halterman8a0b3972017-08-15 16:14:18 -07001124 removalTimestamp.compareTo(timestampToCheck) > 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001125 // removalRequest is more recent
1126 return true;
1127 }
1128 return false;
1129 }
1130
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001131 /**
1132 * Returns a Device, merging description given from multiple Providers.
1133 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001134 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001135 * @param providerDescs Collection of Descriptions from multiple providers
1136 * @return Device instance
1137 */
1138 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001139 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001140
Thomas Vachuska444eda62014-10-28 13:09:42 -07001141 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001142
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001143 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001144
1145 DeviceDescriptions desc = providerDescs.get(primary);
1146
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001147 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001148 Type type = base.type();
1149 String manufacturer = base.manufacturer();
1150 String hwVersion = base.hwVersion();
1151 String swVersion = base.swVersion();
1152 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001153 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001154 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1155 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001156
1157 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1158 if (e.getKey().equals(primary)) {
1159 continue;
1160 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001161 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001162 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001163 // Currently assuming there will never be a key conflict between
1164 // providers
1165
1166 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001167 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001168 }
1169
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001170 return new DefaultDevice(primary, deviceId, type, manufacturer,
1171 hwVersion, swVersion, serialNumber,
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001172 chassisId, annotations.build());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001173 }
1174
Marc De Leenheer88194c32015-05-29 22:10:59 -07001175 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1176 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001177 return new DefaultPort(device, number, isEnabled, description.type(),
1178 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001179 }
1180
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001181 /**
1182 * Returns a Port, merging description given from multiple Providers.
1183 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001184 * @param device device the port is on
1185 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001186 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001187 * @return Port instance
1188 */
1189 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001190 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001191
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001192 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001193 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001194 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001195 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001196 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001197 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001198 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1199 if (portDesc != null) {
1200 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001201 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001202 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001203 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001204 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001205 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001206 if (e.getKey().equals(primary)) {
1207 continue;
1208 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001209 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001210 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001211 // Currently assuming there will never be a key conflict between
1212 // providers
1213
1214 // annotation merging. not so efficient, should revisit later
1215 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1216 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001217 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1218 continue;
1219 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001220 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001221 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001222 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001223 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001224 }
1225 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001226 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001227 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001228 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001229 PortDescription current = portDesc.value();
1230 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001231 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001232 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001233 }
1234
1235 /**
1236 * @return primary ProviderID, or randomly chosen one if none exists
1237 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001238 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001239 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001240 ProviderId fallBackPrimary = null;
1241 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1242 if (!e.getKey().isAncillary()) {
1243 return e.getKey();
1244 } else if (fallBackPrimary == null) {
1245 // pick randomly as a fallback in case there is no primary
1246 fallBackPrimary = e.getKey();
1247 }
1248 }
1249 return fallBackPrimary;
1250 }
1251
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001252 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001253 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001254 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001255 return providerDescs.get(pid);
1256 }
1257
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001258 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001259 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001260 }
1261
Jonathan Hart7d656f42015-01-27 14:07:23 -08001262 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001263 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001264 }
Madan Jampani47c93732014-10-06 20:46:08 -07001265
Jonathan Hart7d656f42015-01-27 14:07:23 -08001266 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001267 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001268 }
1269
Jonathan Hart7d656f42015-01-27 14:07:23 -08001270 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001271 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001272 }
1273
Jonathan Hart7d656f42015-01-27 14:07:23 -08001274 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001275 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001276 }
1277
Jonathan Hart7d656f42015-01-27 14:07:23 -08001278 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001279 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001280 }
1281
Jonathan Hart7d656f42015-01-27 14:07:23 -08001282 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001283 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1284 }
1285
1286 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1287 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001288 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001289 } catch (IOException e) {
1290 log.error("Failed to send" + event + " to " + recipient, e);
1291 }
1292 }
1293
1294 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1295 try {
1296 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1297 } catch (IOException e) {
1298 log.error("Failed to send" + event + " to " + recipient, e);
1299 }
1300 }
1301
1302 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1303 try {
1304 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1305 } catch (IOException e) {
1306 log.error("Failed to send" + event + " to " + recipient, e);
1307 }
1308 }
1309
1310 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1311 try {
1312 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1313 } catch (IOException e) {
1314 log.error("Failed to send" + event + " to " + recipient, e);
1315 }
1316 }
1317
1318 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1319 try {
1320 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1321 } catch (IOException e) {
1322 log.error("Failed to send" + event + " to " + recipient, e);
1323 }
1324 }
1325
1326 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1327 final NodeId self = clusterService.getLocalNode().id();
1328
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001329 final int numDevices = deviceDescs.size();
1330 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1331 final int portsPerDevice = 8; // random factor to minimize reallocation
1332 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1333 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001334
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001335 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001336
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001337 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001338 synchronized (devDescs) {
1339
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001340 // send device offline timestamp
1341 Timestamp lOffline = this.offline.get(deviceId);
1342 if (lOffline != null) {
1343 adOffline.put(deviceId, lOffline);
1344 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001345
1346 for (Entry<ProviderId, DeviceDescriptions>
1347 prov : devDescs.entrySet()) {
1348
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001349 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001350 final ProviderId provId = prov.getKey();
1351 final DeviceDescriptions descs = prov.getValue();
1352
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001353 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001354 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001355
1356 for (Entry<PortNumber, Timestamped<PortDescription>>
1357 portDesc : descs.getPortDescs().entrySet()) {
1358
1359 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001360 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001361 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001362 }
1363 }
1364 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001365 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001366
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001367 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001368 }
1369
1370 /**
1371 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001372 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001373 * Notify sender about out-dated information using regular replication message.
1374 * Send back advertisement to sender if not in sync.
1375 *
1376 * @param advertisement to respond to
1377 */
1378 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1379
1380 final NodeId sender = advertisement.sender();
1381
1382 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1383 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1384 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1385
1386 // Fragments to request
1387 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1388 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1389
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001390 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001391 final DeviceId deviceId = de.getKey();
1392 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1393
1394 synchronized (lDevice) {
1395 // latestTimestamp across provider
1396 // Note: can be null initially
1397 Timestamp localLatest = offline.get(deviceId);
1398
1399 // handle device Ads
1400 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1401 final ProviderId provId = prov.getKey();
1402 final DeviceDescriptions lDeviceDescs = prov.getValue();
1403
1404 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1405
1406
1407 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1408 Timestamp advDevTimestamp = devAds.get(devFragId);
1409
Jonathan Hart403ea932015-02-20 16:23:00 -08001410 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1411 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001412 // remote does not have it or outdated, suggest
1413 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1414 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1415 // local is outdated, request
1416 reqDevices.add(devFragId);
1417 }
1418
1419 // handle port Ads
1420 for (Entry<PortNumber, Timestamped<PortDescription>>
1421 pe : lDeviceDescs.getPortDescs().entrySet()) {
1422
1423 final PortNumber num = pe.getKey();
1424 final Timestamped<PortDescription> lPort = pe.getValue();
1425
1426 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1427
1428 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001429 if (advPortTimestamp == null || lPort.isNewerThan(
1430 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001431 // remote does not have it or outdated, suggest
1432 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1433 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1434 // local is outdated, request
1435 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1436 reqPorts.add(portFragId);
1437 }
1438
1439 // remove port Ad already processed
1440 portAds.remove(portFragId);
1441 } // end local port loop
1442
1443 // remove device Ad already processed
1444 devAds.remove(devFragId);
1445
1446 // find latest and update
1447 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1448 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001449 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001450 localLatest = providerLatest;
1451 }
1452 } // end local provider loop
1453
1454 // checking if remote timestamp is more recent.
1455 Timestamp rOffline = offlineAds.get(deviceId);
1456 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001457 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001458 // remote offline timestamp suggests that the
1459 // device is off-line
1460 markOfflineInternal(deviceId, rOffline);
1461 }
1462
1463 Timestamp lOffline = offline.get(deviceId);
1464 if (lOffline != null && rOffline == null) {
1465 // locally offline, but remote is online, suggest offline
1466 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1467 }
1468
1469 // remove device offline Ad already processed
1470 offlineAds.remove(deviceId);
1471 } // end local device loop
1472 } // device lock
1473
1474 // If there is any Ads left, request them
1475 log.trace("Ads left {}, {}", devAds, portAds);
1476 reqDevices.addAll(devAds.keySet());
1477 reqPorts.addAll(portAds.keySet());
1478
1479 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1480 log.trace("Nothing to request to remote peer {}", sender);
1481 return;
1482 }
1483
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001484 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001485
1486 // 2-way Anti-Entropy for now
1487 try {
1488 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1489 } catch (IOException e) {
1490 log.error("Failed to send response advertisement to " + sender, e);
1491 }
1492
1493// Sketch of 3-way Anti-Entropy
1494// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1495// ClusterMessage message = new ClusterMessage(
1496// clusterService.getLocalNode().id(),
1497// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1498// SERIALIZER.encode(request));
1499//
1500// try {
1501// clusterCommunicator.unicast(message, advertisement.sender());
1502// } catch (IOException e) {
1503// log.error("Failed to send advertisement reply to "
1504// + advertisement.sender(), e);
1505// }
Madan Jampani47c93732014-10-06 20:46:08 -07001506 }
1507
Madan Jampani255a58b2014-10-09 12:08:20 -07001508 private void notifyDelegateIfNotNull(DeviceEvent event) {
1509 if (event != null) {
1510 notifyDelegate(event);
1511 }
1512 }
1513
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001514 private final class SendAdvertisementTask implements Runnable {
1515
1516 @Override
1517 public void run() {
1518 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001519 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001520 return;
1521 }
1522
1523 try {
1524 final NodeId self = clusterService.getLocalNode().id();
1525 Set<ControllerNode> nodes = clusterService.getNodes();
1526
1527 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1528 .transform(toNodeId())
1529 .toList();
1530
1531 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001532 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001533 return;
1534 }
1535
1536 NodeId peer;
1537 do {
1538 int idx = RandomUtils.nextInt(0, nodeIds.size());
1539 peer = nodeIds.get(idx);
1540 } while (peer.equals(self));
1541
1542 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1543
1544 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001545 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001546 return;
1547 }
1548
1549 try {
1550 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1551 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001552 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001553 return;
1554 }
1555 } catch (Exception e) {
1556 // catch all Exception to avoid Scheduled task being suppressed.
1557 log.error("Exception thrown while sending advertisement", e);
1558 }
1559 }
1560 }
1561
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001562 private void handleDeviceEvent(InternalDeviceEvent event) {
1563 ProviderId providerId = event.providerId();
1564 DeviceId deviceId = event.deviceId();
1565 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001566
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001567 try {
1568 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1569 deviceDescription));
1570 } catch (Exception e) {
1571 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001572 }
1573 }
1574
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001575 private void handleDeviceOfflineEvent(InternalDeviceOfflineEvent event) {
1576 DeviceId deviceId = event.deviceId();
1577 Timestamp timestamp = event.timestamp();
Madan Jampani25322532014-10-08 11:20:38 -07001578
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001579 try {
1580 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1581 } catch (Exception e) {
1582 log.warn("Exception thrown handling device offline", e);
Madan Jampani25322532014-10-08 11:20:38 -07001583 }
1584 }
1585
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001586 private void handleRemoveRequest(DeviceId did) {
1587 try {
Jayasree Ghosh7d96d6a2017-02-27 18:35:32 +05301588 DeviceEvent event = removeDevice(did);
1589 notifyDelegateIfNotNull(event);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001590 } catch (Exception e) {
1591 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001592 }
1593 }
1594
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001595 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1596 DeviceId deviceId = event.deviceId();
1597 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001598
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001599 try {
1600 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1601 } catch (Exception e) {
1602 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001603 }
1604 }
1605
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001606 private void handlePortEvent(InternalPortEvent event) {
1607 ProviderId providerId = event.providerId();
1608 DeviceId deviceId = event.deviceId();
1609 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001610
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001611 if (getDevice(deviceId) == null) {
1612 log.debug("{} not found on this node yet, ignoring.", deviceId);
1613 // Note: dropped information will be recovered by anti-entropy
1614 return;
1615 }
Madan Jampani47c93732014-10-06 20:46:08 -07001616
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001617 try {
1618 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1619 } catch (Exception e) {
1620 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001621 }
1622 }
1623
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001624 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1625 ProviderId providerId = event.providerId();
1626 DeviceId deviceId = event.deviceId();
1627 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001628
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001629 if (getDevice(deviceId) == null) {
1630 log.debug("{} not found on this node yet, ignoring.", deviceId);
1631 // Note: dropped information will be recovered by anti-entropy
1632 return;
1633 }
Madan Jampani47c93732014-10-06 20:46:08 -07001634
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001635 try {
1636 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1637 } catch (Exception e) {
1638 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001639 }
1640 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001641
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001642 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1643 try {
1644 handleAdvertisement(advertisement);
1645 } catch (Exception e) {
1646 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001647 }
1648 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001649
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001650 private class InternalPortStatsListener
1651 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1652 @Override
1653 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1654 if (event.type() == PUT) {
1655 Device device = devices.get(event.key());
1656 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001657 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001658 }
1659 }
1660 }
1661 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001662}