blob: 90e115ab21338f5743579f5dd9ef63f145ffce94 [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;
52import org.onosproject.mastership.MastershipTerm;
53import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070054import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.net.AnnotationsUtil;
56import org.onosproject.net.DefaultAnnotations;
57import org.onosproject.net.DefaultDevice;
58import org.onosproject.net.DefaultPort;
59import org.onosproject.net.Device;
60import org.onosproject.net.Device.Type;
61import org.onosproject.net.DeviceId;
62import org.onosproject.net.MastershipRole;
63import org.onosproject.net.Port;
64import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070065import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080066import org.onosproject.net.device.DeviceClockService;
67import org.onosproject.net.device.DeviceDescription;
68import org.onosproject.net.device.DeviceEvent;
69import org.onosproject.net.device.DeviceStore;
70import org.onosproject.net.device.DeviceStoreDelegate;
71import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070072import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080073import org.onosproject.net.provider.ProviderId;
74import org.onosproject.store.AbstractStore;
75import org.onosproject.store.Timestamp;
76import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
Brian O'Connorabafb502014-12-02 22:26:20 -080077import org.onosproject.store.cluster.messaging.MessageSubject;
Jordan Haltermanebedbb52017-08-08 15:57:50 -070078import org.onosproject.store.impl.MastershipBasedTimestamp;
Brian O'Connorabafb502014-12-02 22:26:20 -080079import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070080import org.onosproject.store.serializers.KryoNamespaces;
Brian O'Connor6de2e202015-05-21 14:30:41 -070081import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070082import org.onosproject.store.service.EventuallyConsistentMap;
83import org.onosproject.store.service.EventuallyConsistentMapEvent;
84import org.onosproject.store.service.EventuallyConsistentMapListener;
85import org.onosproject.store.service.MultiValuedTimestamp;
Jordan Haltermanc6c6ef22017-08-20 17:11:41 -070086import org.onosproject.store.service.Serializer;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070087import org.onosproject.store.service.StorageService;
88import org.onosproject.store.service.WallClockTimestamp;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070089import org.slf4j.Logger;
90
Ray Milkey2bf5ea72017-06-01 09:03:34 -070091import com.google.common.collect.FluentIterable;
92import com.google.common.collect.ImmutableList;
93import com.google.common.collect.Maps;
94import com.google.common.collect.Sets;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070095
96import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070097import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070098import static com.google.common.base.Verify.verify;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -080099import static java.util.concurrent.Executors.newCachedThreadPool;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800100import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800101import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800102import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800103import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
Ray Milkey9ef22232016-07-14 12:42:37 -0700104import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED;
105import static org.onosproject.net.device.DeviceEvent.Type.PORT_ADDED;
106import static org.onosproject.net.device.DeviceEvent.Type.PORT_REMOVED;
107import static org.onosproject.net.device.DeviceEvent.Type.PORT_STATS_UPDATED;
108import static org.onosproject.net.device.DeviceEvent.Type.PORT_UPDATED;
109import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700110import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE;
111import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVED;
Ray Milkey9ef22232016-07-14 12:42:37 -0700112import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700113import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_UPDATE;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700114import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE;
115import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_UPDATE;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700116import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800117import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700118
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700119/**
120 * Manages inventory of infrastructure devices using gossip protocol to distribute
121 * information.
122 */
123@Component(immediate = true)
124@Service
125public class GossipDeviceStore
126 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
127 implements DeviceStore {
128
129 private final Logger log = getLogger(getClass());
130
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700131 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800132 // Timeout in milliseconds to process device or ports on remote master node
133 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700134
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700135 // innerMap is used to lock a Device, thus instance should never be replaced.
136 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700137 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700138 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700139
140 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700141 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
142 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700143
144 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200145 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700146 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
147 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700148
149 // to be updated under Device lock
150 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
151 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700152
153 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700154 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700155
156 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700157 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700158
Madan Jampani47c93732014-10-06 20:46:08 -0700159 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700160 protected StorageService storageService;
161
162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700163 protected ClusterCommunicationService clusterCommunicator;
164
Madan Jampani53e44e62014-10-07 12:39:51 -0700165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
166 protected ClusterService clusterService;
167
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700168 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
169 protected MastershipService mastershipService;
170
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800171 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
172 protected MastershipTermService termService;
173
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700174 private static final Timestamp DEFAULT_TIMESTAMP = new MastershipBasedTimestamp(0, 0);
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800175
Jordan Haltermanc6c6ef22017-08-20 17:11:41 -0700176 protected static final Serializer SERIALIZER = Serializer.using(KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800177 .register(DistributedStoreSerializers.STORE_COMMON)
178 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
179 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
180 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700181 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800182 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
183 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700184 .register(DeviceAntiEntropyAdvertisement.class)
185 .register(DeviceFragmentId.class)
186 .register(PortFragmentId.class)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700187 .build("GossipDevice"));
Madan Jampani53e44e62014-10-07 12:39:51 -0700188
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800189 private ExecutorService executor;
190
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800191 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700192
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800193 // TODO make these anti-entropy parameters configurable
194 private long initialDelaySec = 5;
195 private long periodSec = 5;
196
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700197 @Activate
198 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800199 executor = newCachedThreadPool(groupedThreads("onos/device", "fg-%d", log));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800200
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800201 backgroundExecutor =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800202 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d", log)));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700203
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700204 addSubscriber(DEVICE_UPDATE, this::handleDeviceEvent);
205 addSubscriber(DEVICE_OFFLINE, this::handleDeviceOfflineEvent);
206 addSubscriber(DEVICE_REMOVE_REQ, this::handleRemoveRequest);
207 addSubscriber(DEVICE_REMOVED, this::handleDeviceRemovedEvent);
208 addSubscriber(PORT_UPDATE, this::handlePortEvent);
209 addSubscriber(PORT_STATUS_UPDATE, this::handlePortStatusEvent);
210 addSubscriber(DEVICE_ADVERTISE, this::handleDeviceAdvertisement);
Madan Jampani2af244a2015-02-22 13:12:01 -0800211
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700212 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800213 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700214 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700215
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700216 // Create a distributed map for port stats.
217 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
218 .register(KryoNamespaces.API)
HIGUCHI Yuta03666a32016-05-18 11:49:09 -0700219 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
220 .register(MultiValuedTimestamp.class);
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700221
222 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
223 .withName("port-stats")
224 .withSerializer(deviceDataSerializer)
225 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700226 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700227 .withTombstonesDisabled()
228 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200229 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
230 eventuallyConsistentMapBuilder()
231 .withName("port-stats-delta")
232 .withSerializer(deviceDataSerializer)
233 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
234 .withTimestampProvider((k, v) -> new WallClockTimestamp())
235 .withTombstonesDisabled()
236 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700237 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700238 log.info("Started");
239 }
240
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700241 private <M> void addSubscriber(MessageSubject subject, Consumer<M> handler) {
242 clusterCommunicator.addSubscriber(subject, SERIALIZER::decode, handler, executor);
243 }
244
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700245 @Deactivate
246 public void deactivate() {
Frank Wange0eb5ce2016-07-01 18:21:25 +0800247 devicePortStats.removeListener(portStatsListener);
Madan Jampani632f16b2015-08-11 12:42:59 -0700248 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200249 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800250 executor.shutdownNow();
251
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800252 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700253 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800254 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700255 log.error("Timeout during executor shutdown");
256 }
257 } catch (InterruptedException e) {
258 log.error("Error during executor shutdown", e);
259 }
260
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700261 deviceDescs.clear();
262 devices.clear();
263 devicePorts.clear();
264 availableDevices.clear();
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700265 clusterCommunicator.removeSubscriber(DEVICE_UPDATE);
266 clusterCommunicator.removeSubscriber(DEVICE_OFFLINE);
267 clusterCommunicator.removeSubscriber(DEVICE_REMOVE_REQ);
268 clusterCommunicator.removeSubscriber(DEVICE_REMOVED);
269 clusterCommunicator.removeSubscriber(PORT_UPDATE);
270 clusterCommunicator.removeSubscriber(PORT_STATUS_UPDATE);
271 clusterCommunicator.removeSubscriber(DEVICE_ADVERTISE);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700272 log.info("Stopped");
273 }
274
275 @Override
276 public int getDeviceCount() {
277 return devices.size();
278 }
279
280 @Override
mskala0d0c6832017-07-12 11:21:23 +0200281 public int getAvailableDeviceCount() {
282 return availableDevices.size();
283 }
284
285 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700286 public Iterable<Device> getDevices() {
287 return Collections.unmodifiableCollection(devices.values());
288 }
289
290 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800291 public Iterable<Device> getAvailableDevices() {
292 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700293 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800294 }
295
296 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700297 public Device getDevice(DeviceId deviceId) {
298 return devices.get(deviceId);
299 }
300
301 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700302 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700303 DeviceId deviceId,
304 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800305 NodeId localNode = clusterService.getLocalNode().id();
306 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Jordan Halterman4ec25fc2017-12-19 14:56:08 -0800307 boolean isMaster = localNode.equals(deviceNode);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800308
309 // Process device update only if we're the master,
310 // otherwise signal the actual master.
311 DeviceEvent deviceEvent = null;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800312
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700313 // If this node is the master for the device, acquire a new timestamp. Otherwise,
314 // use a 0,0 or tombstone timestamp to create the device if it doesn't already exist.
Jordan Halterman4ec25fc2017-12-19 14:56:08 -0800315 Timestamp newTimestamp;
316 try {
317 newTimestamp = isMaster
318 ? deviceClockService.getTimestamp(deviceId)
319 : removalRequest.getOrDefault(deviceId, DEFAULT_TIMESTAMP);
320 } catch (IllegalStateException e) {
Yuta HIGUCHI1edc36b2018-01-24 23:39:06 -0800321 newTimestamp = removalRequest.getOrDefault(deviceId, DEFAULT_TIMESTAMP);
Jordan Halterman4ec25fc2017-12-19 14:56:08 -0800322 isMaster = false;
323 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700324 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
325 final Timestamped<DeviceDescription> mergedDesc;
326 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800327
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700328 synchronized (device) {
329 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
Jordan Halterman8a0b3972017-08-15 16:14:18 -0700330 if (deviceEvent == null) {
331 return null;
332 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700333 mergedDesc = device.get(providerId).getDeviceDesc();
334 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800335
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700336 // If this node is the master for the device, update peers.
337 if (isMaster) {
Jordan Halterman8a0b3972017-08-15 16:14:18 -0700338 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
339 providerId, deviceId);
340 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700341 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800342
343 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700344 }
345
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700346 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700347 DeviceId deviceId,
348 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700349
350 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800351 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700352 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700353
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800354 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700355 // locking per device
356
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700357 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
358 log.debug("Ignoring outdated event: {}", deltaDesc);
359 return null;
360 }
361
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800362 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700363
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700364 final Device oldDevice = devices.get(deviceId);
365 final Device newDevice;
366
367 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700368 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700369 // on new device or valid update
370 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800371 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700372 } else {
373 // outdated event, ignored.
374 return null;
375 }
376 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700377 // REGISTER
378 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700379 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700380 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700381 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700382 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700383 } else {
384 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700385 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
386 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700387 }
388 }
389 }
390
391 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700392 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700393 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700394 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700395
396 // update composed device cache
397 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
398 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700399 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
400 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700401
402 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700403 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700404 }
405
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700406 log.debug("Device {} added", newDevice.id());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700407 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
408 }
409
410 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700411 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700412 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700413 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700414 Device newDevice, Timestamp newTimestamp,
415 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700416 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700417 boolean propertiesChanged =
418 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700419 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
mskala4b2081a2017-06-12 16:39:50 +0200420 !Objects.equals(oldDevice.providerId(), newDevice.providerId()) ||
421 !Objects.equals(oldDevice.chassisId(), newDevice.chassisId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700422 boolean annotationsChanged =
423 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700424
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700425 // Primary providers can respond to all changes, but ancillary ones
426 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800427 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700428 if ((providerId.isAncillary() && annotationsChanged) ||
429 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700430 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
431 if (!replaced) {
432 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700433 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800434 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700435 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700436
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700437 log.debug("Device {} updated", newDevice.id());
alshabibdc5d8bd2015-11-02 15:41:29 -0800438 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700439 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800440
helenyrwufd296b62016-06-22 17:43:02 -0700441 if (!providerId.isAncillary() && forceAvailable) {
alshabibdc5d8bd2015-11-02 15:41:29 -0800442 boolean wasOnline = availableDevices.contains(newDevice.id());
443 markOnline(newDevice.id(), newTimestamp);
444 if (!wasOnline) {
445 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
446 }
447 }
448 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700449 }
450
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700451 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700452 // update composed device cache
453 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
454 verify(oldDevice == null,
455 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
456 providerId, oldDevice, newDevice);
457
458 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700459 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700460 }
461
462 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
463 }
464
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700465 @Override
466 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700467 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
468 }
469
470 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700471 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700472 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700473 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700474 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800475 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700476 }
477 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700478 }
479
480 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700481 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700482 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700483
484 // locking device
485 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700486 // accept off-line if given timestamp is newer than
487 // the latest Timestamp from Primary provider
488 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
jaegonkim3b5d4162018-01-13 10:52:02 +0900489 if (primDescs != null) {
490 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
491 if (lastTimestamp == null) {
492 lastTimestamp = deviceClockService.getTimestamp(deviceId);
493 }
494 if (timestamp.compareTo(lastTimestamp) <= 0) {
495 // outdated event ignore
496 return null;
497 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700498 }
499
500 offline.put(deviceId, timestamp);
501
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700502 Device device = devices.get(deviceId);
503 if (device == null) {
504 return null;
505 }
506 boolean removed = availableDevices.remove(deviceId);
507 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700508 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700509 }
510 return null;
511 }
512 }
513
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700514 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700515 public boolean markOnline(DeviceId deviceId) {
516 if (devices.containsKey(deviceId)) {
517 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
518 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
519 synchronized (deviceLock) {
520 if (markOnline(deviceId, timestamp)) {
521 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
522 return true;
523 } else {
524 return false;
525 }
526 }
527 }
528 log.warn("Device {} does not exist in store", deviceId);
529 return false;
530
531 }
532
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700533 /**
534 * Marks the device as available if the given timestamp is not outdated,
535 * compared to the time the device has been marked offline.
536 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700537 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700538 * @param timestamp of the event triggering this change.
539 * @return true if availability change request was accepted and changed the state
540 */
541 // Guarded by deviceDescs value (=Device lock)
542 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
543 // accept on-line if given timestamp is newer than
544 // the latest offline request Timestamp
545 Timestamp offlineTimestamp = offline.get(deviceId);
546 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700547 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700548
549 offline.remove(deviceId);
550 return availableDevices.add(deviceId);
551 }
552 return false;
553 }
554
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700555 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700556 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700557 DeviceId deviceId,
558 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700559
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800560 NodeId localNode = clusterService.getLocalNode().id();
561 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
562 // since it will trigger distributed store read.
563 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
564 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
565 // If we don't care much about topology performance, then it might be OK.
566 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700567
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800568 // Process port update only if we're the master of the device,
569 // otherwise signal the actual master.
570 List<DeviceEvent> deviceEvents = null;
571 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700572
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800573 final Timestamp newTimestamp;
574 try {
575 newTimestamp = deviceClockService.getTimestamp(deviceId);
576 } catch (IllegalStateException e) {
577 log.info("Timestamp was not available for device {}", deviceId);
578 log.debug(" discarding {}", portDescriptions);
579 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700580
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800581 // Possible situation:
582 // Device connected and became master for short period of time,
583 // but lost mastership before this instance had the chance to
584 // retrieve term information.
585
586 // Information dropped here is expected to be recoverable by
587 // device probing after mastership change
588
589 return Collections.emptyList();
590 }
591 log.debug("timestamp for {} {}", deviceId, newTimestamp);
592
593 final Timestamped<List<PortDescription>> timestampedInput
594 = new Timestamped<>(portDescriptions, newTimestamp);
595 final Timestamped<List<PortDescription>> merged;
596
597 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
598
599 synchronized (device) {
600 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
601 final DeviceDescriptions descs = device.get(providerId);
602 List<PortDescription> mergedList =
603 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700604 .transform(input ->
605 // lookup merged port description
606 descs.getPortDesc(input.portNumber()).value()
607 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700608 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800609 }
610
611 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700612 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700613 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800614 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
615 }
616
617 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700618 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700619 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700620
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800621 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700622 }
623
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700624 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700625 DeviceId deviceId,
626 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700627
628 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700629 if (device == null) {
630 log.debug("Device is no longer valid: {}", deviceId);
631 return Collections.emptyList();
632 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700633
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700634 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700635 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
636
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700637 List<DeviceEvent> events = new ArrayList<>();
638 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700639
640 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
641 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700642 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700643 }
644
645 DeviceDescriptions descs = descsMap.get(providerId);
646 // every provider must provide DeviceDescription.
647 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700648 "Device description for Device ID %s from Provider %s was not found",
649 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700650
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700651 Map<PortNumber, Port> ports = getPortMap(deviceId);
652
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700653 final Timestamp newTimestamp = portDescriptions.timestamp();
654
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700655 // Add new ports
656 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700657 for (PortDescription portDescription : portDescriptions.value()) {
658 final PortNumber number = portDescription.portNumber();
659 processed.add(number);
660
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700661 final Port oldPort = ports.get(number);
662 final Port newPort;
663
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700664
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700665 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
666 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700667 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700668 // on new port or valid update
669 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700670 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700671 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700672 newPort = composePort(device, number, descsMap);
673 } else {
674 // outdated event, ignored.
675 continue;
676 }
677
678 events.add(oldPort == null ?
679 createPort(device, newPort, ports) :
680 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700681 }
682
683 events.addAll(pruneOldPorts(device, ports, processed));
684 }
685 return FluentIterable.from(events).filter(notNull()).toList();
686 }
687
688 // Creates a new port based on the port description adds it to the map and
689 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700690 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700691 private DeviceEvent createPort(Device device, Port newPort,
692 Map<PortNumber, Port> ports) {
693 ports.put(newPort.number(), newPort);
694 return new DeviceEvent(PORT_ADDED, device, newPort);
695 }
696
697 // Checks if the specified port requires update and if so, it replaces the
698 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700699 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700700 private DeviceEvent updatePort(Device device, Port oldPort,
701 Port newPort,
702 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100703
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700704 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700705 oldPort.type() != newPort.type() ||
706 oldPort.portSpeed() != newPort.portSpeed() ||
707 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700708 ports.put(oldPort.number(), newPort);
709 return new DeviceEvent(PORT_UPDATED, device, newPort);
710 }
711 return null;
712 }
713
Michal Machce774332017-01-25 11:02:55 +0100714 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
715
716 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
717 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
718
719 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
720 }
721
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700722 // Prunes the specified list of ports based on which ports are in the
723 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700724 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700725 private List<DeviceEvent> pruneOldPorts(Device device,
726 Map<PortNumber, Port> ports,
727 Set<PortNumber> processed) {
728 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700729 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700730 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700731 Entry<PortNumber, Port> e = iterator.next();
732 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700733 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700734 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700735 iterator.remove();
736 }
737 }
738 return events;
739 }
740
741 // Gets the map of ports for the specified device; if one does not already
742 // exist, it creates and registers a new one.
743 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700744 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700745 }
746
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700747 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700748 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700749 Map<ProviderId, DeviceDescriptions> r;
750 r = deviceDescs.get(deviceId);
751 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700752 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700753 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
754 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
755 if (concurrentlyAdded != null) {
756 r = concurrentlyAdded;
757 }
758 }
759 return r;
760 }
761
762 // Guarded by deviceDescs value (=Device lock)
763 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
764 Map<ProviderId, DeviceDescriptions> device,
765 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700766 synchronized (device) {
767 DeviceDescriptions r = device.get(providerId);
768 if (r == null) {
769 r = new DeviceDescriptions(deltaDesc);
770 device.put(providerId, r);
771 }
772 return r;
773 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700774 }
775
776 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700777 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
778 DeviceId deviceId,
779 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700780 final Timestamp newTimestamp;
781 try {
782 newTimestamp = deviceClockService.getTimestamp(deviceId);
783 } catch (IllegalStateException e) {
784 log.info("Timestamp was not available for device {}", deviceId);
785 log.debug(" discarding {}", portDescription);
786 // Failed to generate timestamp. Ignoring.
787 // See updatePorts comment
788 return null;
789 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700790 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700791 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700792 final DeviceEvent event;
793 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800794 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
795 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700796 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800797 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700798 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700799 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700800 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700801 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700802 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800803 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700804 }
805 return event;
806 }
807
808 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700809 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700810 Device device = devices.get(deviceId);
811 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
812
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700813 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700814 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
815
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700816 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700817
818 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
819 log.debug("Ignoring outdated event: {}", deltaDesc);
820 return null;
821 }
822
823 DeviceDescriptions descs = descsMap.get(providerId);
824 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700825 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700826 "Device description for Device ID %s from Provider %s was not found",
827 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700828
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700829 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
830 final PortNumber number = deltaDesc.value().portNumber();
831 final Port oldPort = ports.get(number);
832 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700833 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100834 boolean toDelete = false;
835
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700836 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700837 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700838 // on new port or valid update
839 // update description
840 descs.putPortDesc(deltaDesc);
841 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100842 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700843 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700844 // same or outdated event, ignored.
845 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700846 return null;
847 }
848
849 if (oldPort == null) {
850 return createPort(device, newPort, ports);
851 } else {
Michal Machce774332017-01-25 11:02:55 +0100852 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700853 }
854 }
855 }
856
857 @Override
858 public List<Port> getPorts(DeviceId deviceId) {
859 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
860 if (ports == null) {
861 return Collections.emptyList();
862 }
863 return ImmutableList.copyOf(ports.values());
864 }
865
866 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700867 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
868 DeviceId deviceId) {
869 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
870 if (descs == null) {
871 return null;
872 }
873 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
874 final Optional<DeviceDescriptions> devDescs;
875 synchronized (descs) {
876 devDescs = Optional.ofNullable(descs.get(pid));
877 }
878 // DeviceDescriptions is concurrent access-safe
879 return devDescs
880 .map(dd -> dd.getPortDescs().values().stream()
881 .map(Timestamped::value))
882 .orElse(Stream.empty());
883 }
884
885 @Override
sangho538108b2015-04-08 14:29:20 -0700886 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200887 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700888
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200889 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
890 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
891 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
892
893 if (prvStatsMap != null) {
894 for (PortStatistics newStats : newStatsCollection) {
895 PortNumber port = PortNumber.portNumber(newStats.port());
896 PortStatistics prvStats = prvStatsMap.get(port);
897 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
898 PortStatistics deltaStats = builder.build();
899 if (prvStats != null) {
900 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
901 }
902 deltaStatsMap.put(port, deltaStats);
903 newStatsMap.put(port, newStats);
904 }
905 } else {
906 for (PortStatistics newStats : newStatsCollection) {
907 PortNumber port = PortNumber.portNumber(newStats.port());
908 newStatsMap.put(port, newStats);
909 }
sangho538108b2015-04-08 14:29:20 -0700910 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200911 devicePortDeltaStats.put(deviceId, deltaStatsMap);
912 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200913 // DeviceEvent returns null because of InternalPortStatsListener usage
914 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200915 }
916
917 /**
918 * Calculate delta statistics by subtracting previous from new statistics.
919 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700920 * @param deviceId device identifier
921 * @param prvStats previous port statistics
922 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200923 * @return PortStatistics
924 */
925 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
926 // calculate time difference
927 long deltaStatsSec, deltaStatsNano;
928 if (newStats.durationNano() < prvStats.durationNano()) {
929 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
930 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
931 } else {
932 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
933 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
934 }
935 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
936 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
937 .setPort(newStats.port())
938 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
939 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
940 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
941 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
942 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
943 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
944 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
945 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
946 .setDurationSec(deltaStatsSec)
947 .setDurationNano(deltaStatsNano)
948 .build();
949 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700950 }
951
952 @Override
953 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700954 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
955 if (portStats == null) {
956 return Collections.emptyList();
957 }
958 return ImmutableList.copyOf(portStats.values());
959 }
960
961 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530962 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
963 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
964 if (portStatsMap == null) {
965 return null;
966 }
967 PortStatistics portStats = portStatsMap.get(portNumber);
968 return portStats;
969 }
970
971 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200972 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
973 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
974 if (portStats == null) {
975 return Collections.emptyList();
976 }
977 return ImmutableList.copyOf(portStats.values());
978 }
979
980 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530981 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
982 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
983 if (portStatsMap == null) {
984 return null;
985 }
986 PortStatistics portStats = portStatsMap.get(portNumber);
987 return portStats;
988 }
989
990 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700991 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
992 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
993 return ports == null ? null : ports.get(portNumber);
994 }
995
996 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700997 public PortDescription getPortDescription(ProviderId pid,
998 DeviceId deviceId,
999 PortNumber portNumber) {
1000 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1001 if (descs == null) {
1002 return null;
1003 }
1004 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1005 final Optional<DeviceDescriptions> devDescs;
1006 synchronized (descs) {
1007 devDescs = Optional.ofNullable(descs.get(pid));
1008 }
1009 // DeviceDescriptions is concurrent access-safe
1010 return devDescs
1011 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1012 .map(Timestamped::value)
1013 .orElse(null);
1014 }
1015
1016 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001017 public boolean isAvailable(DeviceId deviceId) {
1018 return availableDevices.contains(deviceId);
1019 }
1020
1021 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001022 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001023 final NodeId myId = clusterService.getLocalNode().id();
1024 NodeId master = mastershipService.getMasterFor(deviceId);
1025
1026 // if there exist a master, forward
1027 // if there is no master, try to become one and process
1028
1029 boolean relinquishAtEnd = false;
1030 if (master == null) {
1031 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1032 if (myRole != MastershipRole.NONE) {
1033 relinquishAtEnd = true;
1034 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001035 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001036 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001037 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -07001038 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001039 master = myId;
1040 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001041 }
1042
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001043 boolean isMaster = myId.equals(master);
1044
1045 // If this node is not the master, forward the request.
1046 if (!isMaster) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001047 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001048 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001049
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001050 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001051 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001052 /* error log:
1053 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1054 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001055 }
1056
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001057 // If this node is the master, get a timestamp. Otherwise, default to the current device timestamp.
1058 Timestamp timestamp = isMaster ? deviceClockService.getTimestamp(deviceId) : null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001059
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001060 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001061
1062 // If this node is the master, update peers.
1063 if (isMaster && event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001064 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001065 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001066 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001067 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001068
1069 // Relinquish mastership if acquired to remove the device.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001070 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001071 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001072 mastershipService.relinquishMastership(deviceId);
1073 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001074 return event;
1075 }
1076
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001077 private DeviceEvent removeDeviceInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001078
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001079 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001080 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001081 // accept removal request if given timestamp is newer than
1082 // the latest Timestamp from Primary provider
1083 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001084 if (primDescs == null) {
1085 return null;
1086 }
1087
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001088 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001089
1090 // If no timestamp is set, default the timestamp to the last timestamp for the device.
1091 if (timestamp == null) {
1092 timestamp = lastTimestamp;
1093 }
1094
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001095 if (timestamp.compareTo(lastTimestamp) <= 0) {
1096 // outdated event ignore
1097 return null;
1098 }
1099 removalRequest.put(deviceId, timestamp);
1100
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001101 Device device = devices.remove(deviceId);
1102 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001103 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1104 if (ports != null) {
1105 ports.clear();
1106 }
1107 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001108 descs.clear();
1109 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001110 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001111 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001112 }
1113
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001114 /**
1115 * Checks if given timestamp is superseded by removal request
1116 * with more recent timestamp.
1117 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001118 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001119 * @param timestampToCheck timestamp of an event to check
1120 * @return true if device is already removed
1121 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001122 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1123 Timestamp removalTimestamp = removalRequest.get(deviceId);
1124 if (removalTimestamp != null &&
Jordan Halterman8a0b3972017-08-15 16:14:18 -07001125 removalTimestamp.compareTo(timestampToCheck) > 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001126 // removalRequest is more recent
1127 return true;
1128 }
1129 return false;
1130 }
1131
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001132 /**
1133 * Returns a Device, merging description given from multiple Providers.
1134 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001135 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001136 * @param providerDescs Collection of Descriptions from multiple providers
1137 * @return Device instance
1138 */
1139 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001140 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001141
Thomas Vachuska444eda62014-10-28 13:09:42 -07001142 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001143
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001144 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001145
1146 DeviceDescriptions desc = providerDescs.get(primary);
1147
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001148 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001149 Type type = base.type();
1150 String manufacturer = base.manufacturer();
1151 String hwVersion = base.hwVersion();
1152 String swVersion = base.swVersion();
1153 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001154 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001155 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1156 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001157
1158 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1159 if (e.getKey().equals(primary)) {
1160 continue;
1161 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001162 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001163 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001164 // Currently assuming there will never be a key conflict between
1165 // providers
1166
1167 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001168 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001169 }
1170
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001171 return new DefaultDevice(primary, deviceId, type, manufacturer,
1172 hwVersion, swVersion, serialNumber,
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001173 chassisId, annotations.build());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001174 }
1175
Marc De Leenheer88194c32015-05-29 22:10:59 -07001176 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1177 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001178 return new DefaultPort(device, number, isEnabled, description.type(),
1179 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001180 }
1181
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001182 /**
1183 * Returns a Port, merging description given from multiple Providers.
1184 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001185 * @param device device the port is on
1186 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001187 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001188 * @return Port instance
1189 */
1190 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001191 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001192
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001193 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001194 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001195 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001196 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001197 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001198 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001199 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1200 if (portDesc != null) {
1201 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001202 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001203 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001204 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001205 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001206 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001207 if (e.getKey().equals(primary)) {
1208 continue;
1209 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001210 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001211 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001212 // Currently assuming there will never be a key conflict between
1213 // providers
1214
1215 // annotation merging. not so efficient, should revisit later
1216 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1217 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001218 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1219 continue;
1220 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001221 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001222 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001223 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001224 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001225 }
1226 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001227 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001228 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001229 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001230 PortDescription current = portDesc.value();
1231 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001232 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001233 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001234 }
1235
1236 /**
1237 * @return primary ProviderID, or randomly chosen one if none exists
1238 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001239 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001240 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001241 ProviderId fallBackPrimary = null;
1242 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1243 if (!e.getKey().isAncillary()) {
1244 return e.getKey();
1245 } else if (fallBackPrimary == null) {
1246 // pick randomly as a fallback in case there is no primary
1247 fallBackPrimary = e.getKey();
1248 }
1249 }
1250 return fallBackPrimary;
1251 }
1252
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001253 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001254 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001255 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001256 return providerDescs.get(pid);
1257 }
1258
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001259 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001260 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001261 }
1262
Jonathan Hart7d656f42015-01-27 14:07:23 -08001263 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001264 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001265 }
Madan Jampani47c93732014-10-06 20:46:08 -07001266
Jonathan Hart7d656f42015-01-27 14:07:23 -08001267 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001268 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001269 }
1270
Jonathan Hart7d656f42015-01-27 14:07:23 -08001271 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001272 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001273 }
1274
Jonathan Hart7d656f42015-01-27 14:07:23 -08001275 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001276 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001277 }
1278
Jonathan Hart7d656f42015-01-27 14:07:23 -08001279 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001280 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001281 }
1282
Jonathan Hart7d656f42015-01-27 14:07:23 -08001283 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001284 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1285 }
1286
1287 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1288 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001289 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001290 } catch (IOException e) {
1291 log.error("Failed to send" + event + " to " + recipient, e);
1292 }
1293 }
1294
1295 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1296 try {
1297 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1298 } catch (IOException e) {
1299 log.error("Failed to send" + event + " to " + recipient, e);
1300 }
1301 }
1302
1303 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1304 try {
1305 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1306 } catch (IOException e) {
1307 log.error("Failed to send" + event + " to " + recipient, e);
1308 }
1309 }
1310
1311 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1312 try {
1313 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1314 } catch (IOException e) {
1315 log.error("Failed to send" + event + " to " + recipient, e);
1316 }
1317 }
1318
1319 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1320 try {
1321 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1322 } catch (IOException e) {
1323 log.error("Failed to send" + event + " to " + recipient, e);
1324 }
1325 }
1326
1327 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1328 final NodeId self = clusterService.getLocalNode().id();
1329
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001330 final int numDevices = deviceDescs.size();
1331 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1332 final int portsPerDevice = 8; // random factor to minimize reallocation
1333 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1334 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001335
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001336 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001337
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001338 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001339 synchronized (devDescs) {
1340
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001341 // send device offline timestamp
1342 Timestamp lOffline = this.offline.get(deviceId);
1343 if (lOffline != null) {
1344 adOffline.put(deviceId, lOffline);
1345 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001346
1347 for (Entry<ProviderId, DeviceDescriptions>
1348 prov : devDescs.entrySet()) {
1349
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001350 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001351 final ProviderId provId = prov.getKey();
1352 final DeviceDescriptions descs = prov.getValue();
1353
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001354 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001355 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001356
1357 for (Entry<PortNumber, Timestamped<PortDescription>>
1358 portDesc : descs.getPortDescs().entrySet()) {
1359
1360 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001361 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001362 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001363 }
1364 }
1365 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001366 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001367
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001368 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001369 }
1370
1371 /**
1372 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001373 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001374 * Notify sender about out-dated information using regular replication message.
1375 * Send back advertisement to sender if not in sync.
1376 *
1377 * @param advertisement to respond to
1378 */
1379 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1380
1381 final NodeId sender = advertisement.sender();
1382
1383 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1384 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1385 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1386
1387 // Fragments to request
1388 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1389 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1390
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001391 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001392 final DeviceId deviceId = de.getKey();
1393 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1394
1395 synchronized (lDevice) {
1396 // latestTimestamp across provider
1397 // Note: can be null initially
1398 Timestamp localLatest = offline.get(deviceId);
1399
1400 // handle device Ads
1401 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1402 final ProviderId provId = prov.getKey();
1403 final DeviceDescriptions lDeviceDescs = prov.getValue();
1404
1405 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1406
1407
1408 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1409 Timestamp advDevTimestamp = devAds.get(devFragId);
1410
Jonathan Hart403ea932015-02-20 16:23:00 -08001411 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1412 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001413 // remote does not have it or outdated, suggest
1414 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1415 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1416 // local is outdated, request
1417 reqDevices.add(devFragId);
1418 }
1419
1420 // handle port Ads
1421 for (Entry<PortNumber, Timestamped<PortDescription>>
1422 pe : lDeviceDescs.getPortDescs().entrySet()) {
1423
1424 final PortNumber num = pe.getKey();
1425 final Timestamped<PortDescription> lPort = pe.getValue();
1426
1427 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1428
1429 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001430 if (advPortTimestamp == null || lPort.isNewerThan(
1431 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001432 // remote does not have it or outdated, suggest
1433 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1434 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1435 // local is outdated, request
1436 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1437 reqPorts.add(portFragId);
1438 }
1439
1440 // remove port Ad already processed
1441 portAds.remove(portFragId);
1442 } // end local port loop
1443
1444 // remove device Ad already processed
1445 devAds.remove(devFragId);
1446
1447 // find latest and update
1448 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1449 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001450 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001451 localLatest = providerLatest;
1452 }
1453 } // end local provider loop
1454
1455 // checking if remote timestamp is more recent.
1456 Timestamp rOffline = offlineAds.get(deviceId);
jaegonkim3b5d4162018-01-13 10:52:02 +09001457 if (localLatest == null || (rOffline != null && 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}