blob: ded0f314620bbcde7de4e2f4020b2cdde4a0b505 [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) {
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -0800320 newTimestamp = removalRequest.getOrDefault(deviceId, DEFAULT_TIMESTAMP);
Jordan Haltermanf9f55632017-12-19 14:56:08 -0800321 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);
jaegonkim73c21bd2018-01-13 10:52:02 +0900488 if (primDescs != null) {
489 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
490 if (lastTimestamp == null) {
491 lastTimestamp = deviceClockService.getTimestamp(deviceId);
492 }
493 if (timestamp.compareTo(lastTimestamp) <= 0) {
494 // outdated event ignore
495 return null;
496 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700497 }
498
499 offline.put(deviceId, timestamp);
500
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700501 Device device = devices.get(deviceId);
502 if (device == null) {
503 return null;
504 }
505 boolean removed = availableDevices.remove(deviceId);
506 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700507 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700508 }
509 return null;
510 }
511 }
512
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700513 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700514 public boolean markOnline(DeviceId deviceId) {
515 if (devices.containsKey(deviceId)) {
516 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
517 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
518 synchronized (deviceLock) {
519 if (markOnline(deviceId, timestamp)) {
520 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
521 return true;
522 } else {
523 return false;
524 }
525 }
526 }
527 log.warn("Device {} does not exist in store", deviceId);
528 return false;
529
530 }
531
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700532 /**
533 * Marks the device as available if the given timestamp is not outdated,
534 * compared to the time the device has been marked offline.
535 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700536 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700537 * @param timestamp of the event triggering this change.
538 * @return true if availability change request was accepted and changed the state
539 */
540 // Guarded by deviceDescs value (=Device lock)
541 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
542 // accept on-line if given timestamp is newer than
543 // the latest offline request Timestamp
544 Timestamp offlineTimestamp = offline.get(deviceId);
545 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700546 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700547
548 offline.remove(deviceId);
549 return availableDevices.add(deviceId);
550 }
551 return false;
552 }
553
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700554 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700555 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700556 DeviceId deviceId,
557 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700558
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800559 NodeId localNode = clusterService.getLocalNode().id();
560 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
561 // since it will trigger distributed store read.
562 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
563 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
564 // If we don't care much about topology performance, then it might be OK.
565 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700566
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800567 // Process port update only if we're the master of the device,
568 // otherwise signal the actual master.
569 List<DeviceEvent> deviceEvents = null;
570 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700571
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800572 final Timestamp newTimestamp;
573 try {
574 newTimestamp = deviceClockService.getTimestamp(deviceId);
575 } catch (IllegalStateException e) {
576 log.info("Timestamp was not available for device {}", deviceId);
577 log.debug(" discarding {}", portDescriptions);
578 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700579
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800580 // Possible situation:
581 // Device connected and became master for short period of time,
582 // but lost mastership before this instance had the chance to
583 // retrieve term information.
584
585 // Information dropped here is expected to be recoverable by
586 // device probing after mastership change
587
588 return Collections.emptyList();
589 }
590 log.debug("timestamp for {} {}", deviceId, newTimestamp);
591
592 final Timestamped<List<PortDescription>> timestampedInput
593 = new Timestamped<>(portDescriptions, newTimestamp);
594 final Timestamped<List<PortDescription>> merged;
595
596 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
597
598 synchronized (device) {
599 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
600 final DeviceDescriptions descs = device.get(providerId);
601 List<PortDescription> mergedList =
602 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700603 .transform(input ->
604 // lookup merged port description
605 descs.getPortDesc(input.portNumber()).value()
606 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700607 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800608 }
609
610 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700611 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700612 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800613 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
614 }
615
616 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700617 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700618 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700619
Ray Milkeyfe0e0852018-01-18 11:14:05 -0800620 return deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700621 }
622
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700623 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700624 DeviceId deviceId,
625 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700626
627 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700628 if (device == null) {
629 log.debug("Device is no longer valid: {}", deviceId);
630 return Collections.emptyList();
631 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700632
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700633 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700634 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
635
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700636 List<DeviceEvent> events = new ArrayList<>();
637 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700638
639 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
640 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700641 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700642 }
643
644 DeviceDescriptions descs = descsMap.get(providerId);
645 // every provider must provide DeviceDescription.
646 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700647 "Device description for Device ID %s from Provider %s was not found",
648 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700649
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700650 Map<PortNumber, Port> ports = getPortMap(deviceId);
651
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700652 final Timestamp newTimestamp = portDescriptions.timestamp();
653
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700654 // Add new ports
655 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700656 for (PortDescription portDescription : portDescriptions.value()) {
657 final PortNumber number = portDescription.portNumber();
658 processed.add(number);
659
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700660 final Port oldPort = ports.get(number);
661 final Port newPort;
662
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700663
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700664 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
665 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700666 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700667 // on new port or valid update
668 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700669 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700670 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700671 newPort = composePort(device, number, descsMap);
672 } else {
673 // outdated event, ignored.
674 continue;
675 }
676
677 events.add(oldPort == null ?
678 createPort(device, newPort, ports) :
679 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700680 }
681
682 events.addAll(pruneOldPorts(device, ports, processed));
683 }
684 return FluentIterable.from(events).filter(notNull()).toList();
685 }
686
687 // Creates a new port based on the port description adds it to the map and
688 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700689 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700690 private DeviceEvent createPort(Device device, Port newPort,
691 Map<PortNumber, Port> ports) {
692 ports.put(newPort.number(), newPort);
693 return new DeviceEvent(PORT_ADDED, device, newPort);
694 }
695
696 // Checks if the specified port requires update and if so, it replaces the
697 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700698 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700699 private DeviceEvent updatePort(Device device, Port oldPort,
700 Port newPort,
701 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100702
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700703 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700704 oldPort.type() != newPort.type() ||
705 oldPort.portSpeed() != newPort.portSpeed() ||
706 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700707 ports.put(oldPort.number(), newPort);
708 return new DeviceEvent(PORT_UPDATED, device, newPort);
709 }
710 return null;
711 }
712
Michal Machce774332017-01-25 11:02:55 +0100713 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
714
715 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
716 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
717
718 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
719 }
720
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700721 // Prunes the specified list of ports based on which ports are in the
722 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700723 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700724 private List<DeviceEvent> pruneOldPorts(Device device,
725 Map<PortNumber, Port> ports,
726 Set<PortNumber> processed) {
727 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700728 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700729 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700730 Entry<PortNumber, Port> e = iterator.next();
731 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700732 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700733 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700734 iterator.remove();
735 }
736 }
737 return events;
738 }
739
740 // Gets the map of ports for the specified device; if one does not already
741 // exist, it creates and registers a new one.
742 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700743 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700744 }
745
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700746 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700747 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700748 Map<ProviderId, DeviceDescriptions> r;
749 r = deviceDescs.get(deviceId);
750 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700751 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700752 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
753 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
754 if (concurrentlyAdded != null) {
755 r = concurrentlyAdded;
756 }
757 }
758 return r;
759 }
760
761 // Guarded by deviceDescs value (=Device lock)
762 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
763 Map<ProviderId, DeviceDescriptions> device,
764 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700765 synchronized (device) {
766 DeviceDescriptions r = device.get(providerId);
767 if (r == null) {
768 r = new DeviceDescriptions(deltaDesc);
769 device.put(providerId, r);
770 }
771 return r;
772 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700773 }
774
775 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700776 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
777 DeviceId deviceId,
778 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700779 final Timestamp newTimestamp;
780 try {
781 newTimestamp = deviceClockService.getTimestamp(deviceId);
782 } catch (IllegalStateException e) {
783 log.info("Timestamp was not available for device {}", deviceId);
784 log.debug(" discarding {}", portDescription);
785 // Failed to generate timestamp. Ignoring.
786 // See updatePorts comment
787 return null;
788 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700789 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700790 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700791 final DeviceEvent event;
792 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800793 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
794 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700795 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800796 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700797 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700798 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700799 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700800 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700801 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800802 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700803 }
804 return event;
805 }
806
807 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700808 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700809 Device device = devices.get(deviceId);
810 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
811
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700812 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700813 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
814
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700815 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700816
817 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
818 log.debug("Ignoring outdated event: {}", deltaDesc);
819 return null;
820 }
821
822 DeviceDescriptions descs = descsMap.get(providerId);
823 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700824 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700825 "Device description for Device ID %s from Provider %s was not found",
826 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700827
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700828 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
829 final PortNumber number = deltaDesc.value().portNumber();
830 final Port oldPort = ports.get(number);
831 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700832 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100833 boolean toDelete = false;
834
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700835 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700836 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700837 // on new port or valid update
838 // update description
839 descs.putPortDesc(deltaDesc);
840 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100841 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700842 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700843 // same or outdated event, ignored.
844 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700845 return null;
846 }
847
848 if (oldPort == null) {
849 return createPort(device, newPort, ports);
850 } else {
Michal Machce774332017-01-25 11:02:55 +0100851 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700852 }
853 }
854 }
855
856 @Override
857 public List<Port> getPorts(DeviceId deviceId) {
858 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
859 if (ports == null) {
860 return Collections.emptyList();
861 }
862 return ImmutableList.copyOf(ports.values());
863 }
864
865 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700866 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
867 DeviceId deviceId) {
868 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
869 if (descs == null) {
870 return null;
871 }
872 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
873 final Optional<DeviceDescriptions> devDescs;
874 synchronized (descs) {
875 devDescs = Optional.ofNullable(descs.get(pid));
876 }
877 // DeviceDescriptions is concurrent access-safe
878 return devDescs
879 .map(dd -> dd.getPortDescs().values().stream()
880 .map(Timestamped::value))
881 .orElse(Stream.empty());
882 }
883
884 @Override
sangho538108b2015-04-08 14:29:20 -0700885 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200886 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700887
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200888 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
889 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
890 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
891
892 if (prvStatsMap != null) {
893 for (PortStatistics newStats : newStatsCollection) {
894 PortNumber port = PortNumber.portNumber(newStats.port());
895 PortStatistics prvStats = prvStatsMap.get(port);
896 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
897 PortStatistics deltaStats = builder.build();
898 if (prvStats != null) {
899 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
900 }
901 deltaStatsMap.put(port, deltaStats);
902 newStatsMap.put(port, newStats);
903 }
904 } else {
905 for (PortStatistics newStats : newStatsCollection) {
906 PortNumber port = PortNumber.portNumber(newStats.port());
907 newStatsMap.put(port, newStats);
908 }
sangho538108b2015-04-08 14:29:20 -0700909 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200910 devicePortDeltaStats.put(deviceId, deltaStatsMap);
911 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200912 // DeviceEvent returns null because of InternalPortStatsListener usage
913 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200914 }
915
916 /**
917 * Calculate delta statistics by subtracting previous from new statistics.
918 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700919 * @param deviceId device identifier
920 * @param prvStats previous port statistics
921 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200922 * @return PortStatistics
923 */
924 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
925 // calculate time difference
926 long deltaStatsSec, deltaStatsNano;
927 if (newStats.durationNano() < prvStats.durationNano()) {
928 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
929 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
930 } else {
931 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
932 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
933 }
934 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
935 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
936 .setPort(newStats.port())
937 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
938 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
939 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
940 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
941 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
942 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
943 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
944 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
945 .setDurationSec(deltaStatsSec)
946 .setDurationNano(deltaStatsNano)
947 .build();
948 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700949 }
950
951 @Override
952 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700953 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
954 if (portStats == null) {
955 return Collections.emptyList();
956 }
957 return ImmutableList.copyOf(portStats.values());
958 }
959
960 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530961 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
962 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
963 if (portStatsMap == null) {
964 return null;
965 }
966 PortStatistics portStats = portStatsMap.get(portNumber);
967 return portStats;
968 }
969
970 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200971 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
972 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
973 if (portStats == null) {
974 return Collections.emptyList();
975 }
976 return ImmutableList.copyOf(portStats.values());
977 }
978
979 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530980 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
981 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
982 if (portStatsMap == null) {
983 return null;
984 }
985 PortStatistics portStats = portStatsMap.get(portNumber);
986 return portStats;
987 }
988
989 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700990 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
991 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
992 return ports == null ? null : ports.get(portNumber);
993 }
994
995 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700996 public PortDescription getPortDescription(ProviderId pid,
997 DeviceId deviceId,
998 PortNumber portNumber) {
999 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1000 if (descs == null) {
1001 return null;
1002 }
1003 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1004 final Optional<DeviceDescriptions> devDescs;
1005 synchronized (descs) {
1006 devDescs = Optional.ofNullable(descs.get(pid));
1007 }
1008 // DeviceDescriptions is concurrent access-safe
1009 return devDescs
1010 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1011 .map(Timestamped::value)
1012 .orElse(null);
1013 }
1014
1015 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001016 public boolean isAvailable(DeviceId deviceId) {
1017 return availableDevices.contains(deviceId);
1018 }
1019
1020 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001021 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001022 final NodeId myId = clusterService.getLocalNode().id();
1023 NodeId master = mastershipService.getMasterFor(deviceId);
1024
1025 // if there exist a master, forward
1026 // if there is no master, try to become one and process
1027
1028 boolean relinquishAtEnd = false;
1029 if (master == null) {
1030 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1031 if (myRole != MastershipRole.NONE) {
1032 relinquishAtEnd = true;
1033 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001034 log.debug("Temporarily requesting role for {} to remove", deviceId);
Jordan Haltermanf1c602d2017-10-18 11:26:52 -07001035 if (mastershipService.requestRoleFor(deviceId).join() == MastershipRole.MASTER) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001036 master = myId;
1037 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001038 }
1039
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001040 boolean isMaster = myId.equals(master);
1041
1042 // If this node is not the master, forward the request.
1043 if (!isMaster) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001044 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001045 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001046
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001047 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001048 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001049 /* error log:
1050 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1051 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001052 }
1053
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001054 // If this node is the master, get a timestamp. Otherwise, default to the current device timestamp.
1055 Timestamp timestamp = isMaster ? deviceClockService.getTimestamp(deviceId) : null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001056
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001057 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001058
1059 // If this node is the master, update peers.
1060 if (isMaster && event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001061 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001062 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001063 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001064 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001065
1066 // Relinquish mastership if acquired to remove the device.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001067 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001068 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001069 mastershipService.relinquishMastership(deviceId);
1070 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001071 return event;
1072 }
1073
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001074 private DeviceEvent removeDeviceInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001075
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001076 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001077 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001078 // accept removal request if given timestamp is newer than
1079 // the latest Timestamp from Primary provider
1080 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001081 if (primDescs == null) {
1082 return null;
1083 }
1084
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001085 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001086
1087 // If no timestamp is set, default the timestamp to the last timestamp for the device.
1088 if (timestamp == null) {
1089 timestamp = lastTimestamp;
1090 }
1091
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001092 if (timestamp.compareTo(lastTimestamp) <= 0) {
1093 // outdated event ignore
1094 return null;
1095 }
1096 removalRequest.put(deviceId, timestamp);
1097
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001098 Device device = devices.remove(deviceId);
1099 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001100 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1101 if (ports != null) {
1102 ports.clear();
1103 }
1104 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001105 descs.clear();
1106 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001107 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001108 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001109 }
1110
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001111 /**
1112 * Checks if given timestamp is superseded by removal request
1113 * with more recent timestamp.
1114 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001115 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001116 * @param timestampToCheck timestamp of an event to check
1117 * @return true if device is already removed
1118 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001119 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1120 Timestamp removalTimestamp = removalRequest.get(deviceId);
1121 if (removalTimestamp != null &&
Jordan Halterman8a0b3972017-08-15 16:14:18 -07001122 removalTimestamp.compareTo(timestampToCheck) > 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001123 // removalRequest is more recent
1124 return true;
1125 }
1126 return false;
1127 }
1128
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001129 /**
1130 * Returns a Device, merging description given from multiple Providers.
1131 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001132 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001133 * @param providerDescs Collection of Descriptions from multiple providers
1134 * @return Device instance
1135 */
1136 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001137 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001138
Thomas Vachuska444eda62014-10-28 13:09:42 -07001139 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001140
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001141 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001142
1143 DeviceDescriptions desc = providerDescs.get(primary);
1144
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001145 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001146 Type type = base.type();
1147 String manufacturer = base.manufacturer();
1148 String hwVersion = base.hwVersion();
1149 String swVersion = base.swVersion();
1150 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001151 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001152 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1153 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001154
1155 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1156 if (e.getKey().equals(primary)) {
1157 continue;
1158 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001159 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001160 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001161 // Currently assuming there will never be a key conflict between
1162 // providers
1163
1164 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001165 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001166 }
1167
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001168 return new DefaultDevice(primary, deviceId, type, manufacturer,
1169 hwVersion, swVersion, serialNumber,
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001170 chassisId, annotations.build());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001171 }
1172
Marc De Leenheer88194c32015-05-29 22:10:59 -07001173 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1174 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001175 return new DefaultPort(device, number, isEnabled, description.type(),
1176 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001177 }
1178
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001179 /**
1180 * Returns a Port, merging description given from multiple Providers.
1181 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001182 * @param device device the port is on
1183 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001184 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001185 * @return Port instance
1186 */
1187 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001188 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001189
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001190 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001191 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001192 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001193 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001194 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001195 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001196 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1197 if (portDesc != null) {
1198 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001199 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001200 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001201 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001202 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001203 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001204 if (e.getKey().equals(primary)) {
1205 continue;
1206 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001207 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001208 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001209 // Currently assuming there will never be a key conflict between
1210 // providers
1211
1212 // annotation merging. not so efficient, should revisit later
1213 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1214 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001215 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1216 continue;
1217 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001218 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001219 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001220 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001221 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001222 }
1223 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001224 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001225 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001226 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001227 PortDescription current = portDesc.value();
1228 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001229 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001230 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001231 }
1232
1233 /**
1234 * @return primary ProviderID, or randomly chosen one if none exists
1235 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001236 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001237 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001238 ProviderId fallBackPrimary = null;
1239 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1240 if (!e.getKey().isAncillary()) {
1241 return e.getKey();
1242 } else if (fallBackPrimary == null) {
1243 // pick randomly as a fallback in case there is no primary
1244 fallBackPrimary = e.getKey();
1245 }
1246 }
1247 return fallBackPrimary;
1248 }
1249
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001250 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001251 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001252 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001253 return providerDescs.get(pid);
1254 }
1255
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001256 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001257 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001258 }
1259
Jonathan Hart7d656f42015-01-27 14:07:23 -08001260 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001261 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001262 }
Madan Jampani47c93732014-10-06 20:46:08 -07001263
Jonathan Hart7d656f42015-01-27 14:07:23 -08001264 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001265 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001266 }
1267
Jonathan Hart7d656f42015-01-27 14:07:23 -08001268 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001269 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001270 }
1271
Jonathan Hart7d656f42015-01-27 14:07:23 -08001272 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001273 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001274 }
1275
Jonathan Hart7d656f42015-01-27 14:07:23 -08001276 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001277 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001278 }
1279
Jonathan Hart7d656f42015-01-27 14:07:23 -08001280 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001281 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1282 }
1283
1284 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1285 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001286 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001287 } catch (IOException e) {
1288 log.error("Failed to send" + event + " to " + recipient, e);
1289 }
1290 }
1291
1292 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1293 try {
1294 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1295 } catch (IOException e) {
1296 log.error("Failed to send" + event + " to " + recipient, e);
1297 }
1298 }
1299
1300 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1301 try {
1302 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1303 } catch (IOException e) {
1304 log.error("Failed to send" + event + " to " + recipient, e);
1305 }
1306 }
1307
1308 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1309 try {
1310 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1311 } catch (IOException e) {
1312 log.error("Failed to send" + event + " to " + recipient, e);
1313 }
1314 }
1315
1316 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1317 try {
1318 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1319 } catch (IOException e) {
1320 log.error("Failed to send" + event + " to " + recipient, e);
1321 }
1322 }
1323
1324 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1325 final NodeId self = clusterService.getLocalNode().id();
1326
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001327 final int numDevices = deviceDescs.size();
1328 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1329 final int portsPerDevice = 8; // random factor to minimize reallocation
1330 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1331 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001332
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001333 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001334
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001335 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001336 synchronized (devDescs) {
1337
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001338 // send device offline timestamp
1339 Timestamp lOffline = this.offline.get(deviceId);
1340 if (lOffline != null) {
1341 adOffline.put(deviceId, lOffline);
1342 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001343
1344 for (Entry<ProviderId, DeviceDescriptions>
1345 prov : devDescs.entrySet()) {
1346
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001347 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001348 final ProviderId provId = prov.getKey();
1349 final DeviceDescriptions descs = prov.getValue();
1350
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001351 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001352 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001353
1354 for (Entry<PortNumber, Timestamped<PortDescription>>
1355 portDesc : descs.getPortDescs().entrySet()) {
1356
1357 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001358 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001359 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001360 }
1361 }
1362 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001363 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001364
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001365 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001366 }
1367
1368 /**
1369 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001370 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001371 * Notify sender about out-dated information using regular replication message.
1372 * Send back advertisement to sender if not in sync.
1373 *
1374 * @param advertisement to respond to
1375 */
1376 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1377
1378 final NodeId sender = advertisement.sender();
1379
1380 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1381 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1382 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1383
1384 // Fragments to request
1385 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1386 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1387
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001388 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001389 final DeviceId deviceId = de.getKey();
1390 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1391
1392 synchronized (lDevice) {
1393 // latestTimestamp across provider
1394 // Note: can be null initially
1395 Timestamp localLatest = offline.get(deviceId);
1396
1397 // handle device Ads
1398 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1399 final ProviderId provId = prov.getKey();
1400 final DeviceDescriptions lDeviceDescs = prov.getValue();
1401
1402 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1403
1404
1405 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1406 Timestamp advDevTimestamp = devAds.get(devFragId);
1407
Jonathan Hart403ea932015-02-20 16:23:00 -08001408 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1409 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001410 // remote does not have it or outdated, suggest
1411 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1412 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1413 // local is outdated, request
1414 reqDevices.add(devFragId);
1415 }
1416
1417 // handle port Ads
1418 for (Entry<PortNumber, Timestamped<PortDescription>>
1419 pe : lDeviceDescs.getPortDescs().entrySet()) {
1420
1421 final PortNumber num = pe.getKey();
1422 final Timestamped<PortDescription> lPort = pe.getValue();
1423
1424 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1425
1426 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001427 if (advPortTimestamp == null || lPort.isNewerThan(
1428 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001429 // remote does not have it or outdated, suggest
1430 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1431 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1432 // local is outdated, request
1433 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1434 reqPorts.add(portFragId);
1435 }
1436
1437 // remove port Ad already processed
1438 portAds.remove(portFragId);
1439 } // end local port loop
1440
1441 // remove device Ad already processed
1442 devAds.remove(devFragId);
1443
1444 // find latest and update
1445 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1446 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001447 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001448 localLatest = providerLatest;
1449 }
1450 } // end local provider loop
1451
1452 // checking if remote timestamp is more recent.
1453 Timestamp rOffline = offlineAds.get(deviceId);
jaegonkim73c21bd2018-01-13 10:52:02 +09001454 if (localLatest == null || (rOffline != null && rOffline.compareTo(localLatest) > 0)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001455 // remote offline timestamp suggests that the
1456 // device is off-line
1457 markOfflineInternal(deviceId, rOffline);
1458 }
1459
1460 Timestamp lOffline = offline.get(deviceId);
1461 if (lOffline != null && rOffline == null) {
1462 // locally offline, but remote is online, suggest offline
1463 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1464 }
1465
1466 // remove device offline Ad already processed
1467 offlineAds.remove(deviceId);
1468 } // end local device loop
1469 } // device lock
1470
1471 // If there is any Ads left, request them
1472 log.trace("Ads left {}, {}", devAds, portAds);
1473 reqDevices.addAll(devAds.keySet());
1474 reqPorts.addAll(portAds.keySet());
1475
1476 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1477 log.trace("Nothing to request to remote peer {}", sender);
1478 return;
1479 }
1480
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001481 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001482
1483 // 2-way Anti-Entropy for now
1484 try {
1485 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1486 } catch (IOException e) {
1487 log.error("Failed to send response advertisement to " + sender, e);
1488 }
1489
1490// Sketch of 3-way Anti-Entropy
1491// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1492// ClusterMessage message = new ClusterMessage(
1493// clusterService.getLocalNode().id(),
1494// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1495// SERIALIZER.encode(request));
1496//
1497// try {
1498// clusterCommunicator.unicast(message, advertisement.sender());
1499// } catch (IOException e) {
1500// log.error("Failed to send advertisement reply to "
1501// + advertisement.sender(), e);
1502// }
Madan Jampani47c93732014-10-06 20:46:08 -07001503 }
1504
Madan Jampani255a58b2014-10-09 12:08:20 -07001505 private void notifyDelegateIfNotNull(DeviceEvent event) {
1506 if (event != null) {
1507 notifyDelegate(event);
1508 }
1509 }
1510
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001511 private final class SendAdvertisementTask implements Runnable {
1512
1513 @Override
1514 public void run() {
1515 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001516 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001517 return;
1518 }
1519
1520 try {
1521 final NodeId self = clusterService.getLocalNode().id();
1522 Set<ControllerNode> nodes = clusterService.getNodes();
1523
1524 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1525 .transform(toNodeId())
1526 .toList();
1527
1528 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001529 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001530 return;
1531 }
1532
1533 NodeId peer;
1534 do {
1535 int idx = RandomUtils.nextInt(0, nodeIds.size());
1536 peer = nodeIds.get(idx);
1537 } while (peer.equals(self));
1538
1539 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1540
1541 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001542 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001543 return;
1544 }
1545
1546 try {
1547 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1548 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001549 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001550 return;
1551 }
1552 } catch (Exception e) {
1553 // catch all Exception to avoid Scheduled task being suppressed.
1554 log.error("Exception thrown while sending advertisement", e);
1555 }
1556 }
1557 }
1558
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001559 private void handleDeviceEvent(InternalDeviceEvent event) {
1560 ProviderId providerId = event.providerId();
1561 DeviceId deviceId = event.deviceId();
1562 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001563
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001564 try {
1565 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1566 deviceDescription));
1567 } catch (Exception e) {
1568 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001569 }
1570 }
1571
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001572 private void handleDeviceOfflineEvent(InternalDeviceOfflineEvent event) {
1573 DeviceId deviceId = event.deviceId();
1574 Timestamp timestamp = event.timestamp();
Madan Jampani25322532014-10-08 11:20:38 -07001575
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001576 try {
1577 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1578 } catch (Exception e) {
1579 log.warn("Exception thrown handling device offline", e);
Madan Jampani25322532014-10-08 11:20:38 -07001580 }
1581 }
1582
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001583 private void handleRemoveRequest(DeviceId did) {
1584 try {
Jayasree Ghosh7d96d6a2017-02-27 18:35:32 +05301585 DeviceEvent event = removeDevice(did);
1586 notifyDelegateIfNotNull(event);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001587 } catch (Exception e) {
1588 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001589 }
1590 }
1591
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001592 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1593 DeviceId deviceId = event.deviceId();
1594 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001595
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001596 try {
1597 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1598 } catch (Exception e) {
1599 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001600 }
1601 }
1602
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001603 private void handlePortEvent(InternalPortEvent event) {
1604 ProviderId providerId = event.providerId();
1605 DeviceId deviceId = event.deviceId();
1606 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001607
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001608 if (getDevice(deviceId) == null) {
1609 log.debug("{} not found on this node yet, ignoring.", deviceId);
1610 // Note: dropped information will be recovered by anti-entropy
1611 return;
1612 }
Madan Jampani47c93732014-10-06 20:46:08 -07001613
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001614 try {
1615 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1616 } catch (Exception e) {
1617 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001618 }
1619 }
1620
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001621 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1622 ProviderId providerId = event.providerId();
1623 DeviceId deviceId = event.deviceId();
1624 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001625
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001626 if (getDevice(deviceId) == null) {
1627 log.debug("{} not found on this node yet, ignoring.", deviceId);
1628 // Note: dropped information will be recovered by anti-entropy
1629 return;
1630 }
Madan Jampani47c93732014-10-06 20:46:08 -07001631
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001632 try {
1633 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1634 } catch (Exception e) {
1635 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001636 }
1637 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001638
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001639 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1640 try {
1641 handleAdvertisement(advertisement);
1642 } catch (Exception e) {
1643 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001644 }
1645 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001646
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001647 private class InternalPortStatsListener
1648 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1649 @Override
1650 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1651 if (event.type() == PUT) {
1652 Device device = devices.get(event.key());
1653 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001654 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001655 }
1656 }
1657 }
1658 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001659}