blob: 4dd45a8d6be2c9172c67bbccb7e323bf3eb993b4 [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;
HIGUCHI Yutae7290652016-05-18 11:29:01 -070081import org.onosproject.store.serializers.StoreSerializer;
Brian O'Connor6de2e202015-05-21 14:30:41 -070082import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070083import org.onosproject.store.service.EventuallyConsistentMap;
84import org.onosproject.store.service.EventuallyConsistentMapEvent;
85import org.onosproject.store.service.EventuallyConsistentMapListener;
86import org.onosproject.store.service.MultiValuedTimestamp;
87import 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
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700176 protected static final StoreSerializer SERIALIZER = StoreSerializer.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 Haltermanebedbb52017-08-08 15:57:50 -0700307 final 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.
315 final Timestamp newTimestamp = isMaster
316 ? deviceClockService.getTimestamp(deviceId)
317 : removalRequest.getOrDefault(deviceId, DEFAULT_TIMESTAMP);
318 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
319 final Timestamped<DeviceDescription> mergedDesc;
320 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800321
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700322 synchronized (device) {
323 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
324 mergedDesc = device.get(providerId).getDeviceDesc();
325 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800326
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700327 // If this node is the master for the device, update peers.
328 if (isMaster) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800329 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700330 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
helenyrwufd296b62016-06-22 17:43:02 -0700331 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800332 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
333 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800334 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700335 return null;
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700336 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800337
338 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700339 }
340
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700341 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700342 DeviceId deviceId,
343 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700344
345 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800346 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700347 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700348
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800349 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700350 // locking per device
351
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700352 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
353 log.debug("Ignoring outdated event: {}", deltaDesc);
354 return null;
355 }
356
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800357 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700358
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700359 final Device oldDevice = devices.get(deviceId);
360 final Device newDevice;
361
362 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700363 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700364 // on new device or valid update
365 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800366 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700367 } else {
368 // outdated event, ignored.
369 return null;
370 }
371 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700372 // REGISTER
373 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700374 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700375 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700376 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700377 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700378 } else {
379 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700380 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
381 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700382 }
383 }
384 }
385
386 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700387 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700388 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700389 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700390
391 // update composed device cache
392 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
393 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700394 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
395 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700396
397 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700398 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700399 }
400
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700401 log.debug("Device {} added", newDevice.id());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700402 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
403 }
404
405 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700406 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700407 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700408 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700409 Device newDevice, Timestamp newTimestamp,
410 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700411 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700412 boolean propertiesChanged =
413 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700414 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
mskala4b2081a2017-06-12 16:39:50 +0200415 !Objects.equals(oldDevice.providerId(), newDevice.providerId()) ||
416 !Objects.equals(oldDevice.chassisId(), newDevice.chassisId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700417 boolean annotationsChanged =
418 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700419
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700420 // Primary providers can respond to all changes, but ancillary ones
421 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800422 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700423 if ((providerId.isAncillary() && annotationsChanged) ||
424 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700425 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
426 if (!replaced) {
427 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700428 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800429 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700430 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700431
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700432 log.debug("Device {} updated", newDevice.id());
alshabibdc5d8bd2015-11-02 15:41:29 -0800433 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700434 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800435
helenyrwufd296b62016-06-22 17:43:02 -0700436 if (!providerId.isAncillary() && forceAvailable) {
alshabibdc5d8bd2015-11-02 15:41:29 -0800437 boolean wasOnline = availableDevices.contains(newDevice.id());
438 markOnline(newDevice.id(), newTimestamp);
439 if (!wasOnline) {
440 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
441 }
442 }
443 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700444 }
445
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700446 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700447 // update composed device cache
448 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
449 verify(oldDevice == null,
450 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
451 providerId, oldDevice, newDevice);
452
453 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700454 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700455 }
456
457 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
458 }
459
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700460 @Override
461 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700462 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
463 }
464
465 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700466 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700467 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700468 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700469 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800470 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700471 }
472 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700473 }
474
475 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700476 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700477 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700478
479 // locking device
480 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700481 // accept off-line if given timestamp is newer than
482 // the latest Timestamp from Primary provider
483 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
Thomas Vachuska4bd10b92016-12-15 10:13:38 -0800484 if (primDescs == null) {
485 return null;
486 }
487
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700488 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Saritha781984f2017-06-27 09:46:02 +0530489 if (lastTimestamp == null) {
490 lastTimestamp = deviceClockService.getTimestamp(deviceId);
491 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700492 if (timestamp.compareTo(lastTimestamp) <= 0) {
493 // outdated event ignore
494 return null;
495 }
496
497 offline.put(deviceId, timestamp);
498
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700499 Device device = devices.get(deviceId);
500 if (device == null) {
501 return null;
502 }
503 boolean removed = availableDevices.remove(deviceId);
504 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700505 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700506 }
507 return null;
508 }
509 }
510
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700511 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700512 public boolean markOnline(DeviceId deviceId) {
513 if (devices.containsKey(deviceId)) {
514 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
515 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
516 synchronized (deviceLock) {
517 if (markOnline(deviceId, timestamp)) {
518 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
519 return true;
520 } else {
521 return false;
522 }
523 }
524 }
525 log.warn("Device {} does not exist in store", deviceId);
526 return false;
527
528 }
529
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700530 /**
531 * Marks the device as available if the given timestamp is not outdated,
532 * compared to the time the device has been marked offline.
533 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700534 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700535 * @param timestamp of the event triggering this change.
536 * @return true if availability change request was accepted and changed the state
537 */
538 // Guarded by deviceDescs value (=Device lock)
539 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
540 // accept on-line if given timestamp is newer than
541 // the latest offline request Timestamp
542 Timestamp offlineTimestamp = offline.get(deviceId);
543 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700544 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700545
546 offline.remove(deviceId);
547 return availableDevices.add(deviceId);
548 }
549 return false;
550 }
551
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700552 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700553 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700554 DeviceId deviceId,
555 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700556
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800557 NodeId localNode = clusterService.getLocalNode().id();
558 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
559 // since it will trigger distributed store read.
560 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
561 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
562 // If we don't care much about topology performance, then it might be OK.
563 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700564
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800565 // Process port update only if we're the master of the device,
566 // otherwise signal the actual master.
567 List<DeviceEvent> deviceEvents = null;
568 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700569
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800570 final Timestamp newTimestamp;
571 try {
572 newTimestamp = deviceClockService.getTimestamp(deviceId);
573 } catch (IllegalStateException e) {
574 log.info("Timestamp was not available for device {}", deviceId);
575 log.debug(" discarding {}", portDescriptions);
576 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700577
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800578 // Possible situation:
579 // Device connected and became master for short period of time,
580 // but lost mastership before this instance had the chance to
581 // retrieve term information.
582
583 // Information dropped here is expected to be recoverable by
584 // device probing after mastership change
585
586 return Collections.emptyList();
587 }
588 log.debug("timestamp for {} {}", deviceId, newTimestamp);
589
590 final Timestamped<List<PortDescription>> timestampedInput
591 = new Timestamped<>(portDescriptions, newTimestamp);
592 final Timestamped<List<PortDescription>> merged;
593
594 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
595
596 synchronized (device) {
597 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
598 final DeviceDescriptions descs = device.get(providerId);
599 List<PortDescription> mergedList =
600 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700601 .transform(input ->
602 // lookup merged port description
603 descs.getPortDesc(input.portNumber()).value()
604 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700605 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800606 }
607
608 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700609 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700610 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800611 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
612 }
613
614 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700615 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700616 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700617
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800618 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700619 }
620
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700621 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700622 DeviceId deviceId,
623 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700624
625 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700626 if (device == null) {
627 log.debug("Device is no longer valid: {}", deviceId);
628 return Collections.emptyList();
629 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700630
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700631 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700632 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
633
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700634 List<DeviceEvent> events = new ArrayList<>();
635 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700636
637 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
638 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700639 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700640 }
641
642 DeviceDescriptions descs = descsMap.get(providerId);
643 // every provider must provide DeviceDescription.
644 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700645 "Device description for Device ID %s from Provider %s was not found",
646 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700647
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700648 Map<PortNumber, Port> ports = getPortMap(deviceId);
649
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700650 final Timestamp newTimestamp = portDescriptions.timestamp();
651
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700652 // Add new ports
653 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700654 for (PortDescription portDescription : portDescriptions.value()) {
655 final PortNumber number = portDescription.portNumber();
656 processed.add(number);
657
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700658 final Port oldPort = ports.get(number);
659 final Port newPort;
660
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700661
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700662 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
663 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700664 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700665 // on new port or valid update
666 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700667 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700668 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700669 newPort = composePort(device, number, descsMap);
670 } else {
671 // outdated event, ignored.
672 continue;
673 }
674
675 events.add(oldPort == null ?
676 createPort(device, newPort, ports) :
677 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700678 }
679
680 events.addAll(pruneOldPorts(device, ports, processed));
681 }
682 return FluentIterable.from(events).filter(notNull()).toList();
683 }
684
685 // Creates a new port based on the port description adds it to the map and
686 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700687 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700688 private DeviceEvent createPort(Device device, Port newPort,
689 Map<PortNumber, Port> ports) {
690 ports.put(newPort.number(), newPort);
691 return new DeviceEvent(PORT_ADDED, device, newPort);
692 }
693
694 // Checks if the specified port requires update and if so, it replaces the
695 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700696 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700697 private DeviceEvent updatePort(Device device, Port oldPort,
698 Port newPort,
699 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100700
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700701 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700702 oldPort.type() != newPort.type() ||
703 oldPort.portSpeed() != newPort.portSpeed() ||
704 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700705 ports.put(oldPort.number(), newPort);
706 return new DeviceEvent(PORT_UPDATED, device, newPort);
707 }
708 return null;
709 }
710
Michal Machce774332017-01-25 11:02:55 +0100711 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
712
713 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
714 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
715
716 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
717 }
718
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700719 // Prunes the specified list of ports based on which ports are in the
720 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700721 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700722 private List<DeviceEvent> pruneOldPorts(Device device,
723 Map<PortNumber, Port> ports,
724 Set<PortNumber> processed) {
725 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700726 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700727 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700728 Entry<PortNumber, Port> e = iterator.next();
729 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700730 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700731 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700732 iterator.remove();
733 }
734 }
735 return events;
736 }
737
738 // Gets the map of ports for the specified device; if one does not already
739 // exist, it creates and registers a new one.
740 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700741 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700742 }
743
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700744 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700745 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700746 Map<ProviderId, DeviceDescriptions> r;
747 r = deviceDescs.get(deviceId);
748 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700749 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700750 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
751 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
752 if (concurrentlyAdded != null) {
753 r = concurrentlyAdded;
754 }
755 }
756 return r;
757 }
758
759 // Guarded by deviceDescs value (=Device lock)
760 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
761 Map<ProviderId, DeviceDescriptions> device,
762 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700763 synchronized (device) {
764 DeviceDescriptions r = device.get(providerId);
765 if (r == null) {
766 r = new DeviceDescriptions(deltaDesc);
767 device.put(providerId, r);
768 }
769 return r;
770 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700771 }
772
773 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700774 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
775 DeviceId deviceId,
776 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700777 final Timestamp newTimestamp;
778 try {
779 newTimestamp = deviceClockService.getTimestamp(deviceId);
780 } catch (IllegalStateException e) {
781 log.info("Timestamp was not available for device {}", deviceId);
782 log.debug(" discarding {}", portDescription);
783 // Failed to generate timestamp. Ignoring.
784 // See updatePorts comment
785 return null;
786 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700787 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700788 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700789 final DeviceEvent event;
790 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800791 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
792 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700793 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800794 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700795 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700796 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700797 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700798 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700799 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800800 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700801 }
802 return event;
803 }
804
805 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700806 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700807 Device device = devices.get(deviceId);
808 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
809
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700810 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700811 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
812
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700813 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700814
815 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
816 log.debug("Ignoring outdated event: {}", deltaDesc);
817 return null;
818 }
819
820 DeviceDescriptions descs = descsMap.get(providerId);
821 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700822 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700823 "Device description for Device ID %s from Provider %s was not found",
824 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700825
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700826 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
827 final PortNumber number = deltaDesc.value().portNumber();
828 final Port oldPort = ports.get(number);
829 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700830 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100831 boolean toDelete = false;
832
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700833 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700834 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700835 // on new port or valid update
836 // update description
837 descs.putPortDesc(deltaDesc);
838 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100839 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700840 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700841 // same or outdated event, ignored.
842 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700843 return null;
844 }
845
846 if (oldPort == null) {
847 return createPort(device, newPort, ports);
848 } else {
Michal Machce774332017-01-25 11:02:55 +0100849 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700850 }
851 }
852 }
853
854 @Override
855 public List<Port> getPorts(DeviceId deviceId) {
856 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
857 if (ports == null) {
858 return Collections.emptyList();
859 }
860 return ImmutableList.copyOf(ports.values());
861 }
862
863 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700864 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
865 DeviceId deviceId) {
866 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
867 if (descs == null) {
868 return null;
869 }
870 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
871 final Optional<DeviceDescriptions> devDescs;
872 synchronized (descs) {
873 devDescs = Optional.ofNullable(descs.get(pid));
874 }
875 // DeviceDescriptions is concurrent access-safe
876 return devDescs
877 .map(dd -> dd.getPortDescs().values().stream()
878 .map(Timestamped::value))
879 .orElse(Stream.empty());
880 }
881
882 @Override
sangho538108b2015-04-08 14:29:20 -0700883 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200884 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700885
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200886 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
887 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
888 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
889
890 if (prvStatsMap != null) {
891 for (PortStatistics newStats : newStatsCollection) {
892 PortNumber port = PortNumber.portNumber(newStats.port());
893 PortStatistics prvStats = prvStatsMap.get(port);
894 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
895 PortStatistics deltaStats = builder.build();
896 if (prvStats != null) {
897 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
898 }
899 deltaStatsMap.put(port, deltaStats);
900 newStatsMap.put(port, newStats);
901 }
902 } else {
903 for (PortStatistics newStats : newStatsCollection) {
904 PortNumber port = PortNumber.portNumber(newStats.port());
905 newStatsMap.put(port, newStats);
906 }
sangho538108b2015-04-08 14:29:20 -0700907 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200908 devicePortDeltaStats.put(deviceId, deltaStatsMap);
909 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200910 // DeviceEvent returns null because of InternalPortStatsListener usage
911 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200912 }
913
914 /**
915 * Calculate delta statistics by subtracting previous from new statistics.
916 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700917 * @param deviceId device identifier
918 * @param prvStats previous port statistics
919 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200920 * @return PortStatistics
921 */
922 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
923 // calculate time difference
924 long deltaStatsSec, deltaStatsNano;
925 if (newStats.durationNano() < prvStats.durationNano()) {
926 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
927 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
928 } else {
929 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
930 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
931 }
932 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
933 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
934 .setPort(newStats.port())
935 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
936 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
937 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
938 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
939 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
940 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
941 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
942 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
943 .setDurationSec(deltaStatsSec)
944 .setDurationNano(deltaStatsNano)
945 .build();
946 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700947 }
948
949 @Override
950 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700951 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
952 if (portStats == null) {
953 return Collections.emptyList();
954 }
955 return ImmutableList.copyOf(portStats.values());
956 }
957
958 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530959 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
960 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
961 if (portStatsMap == null) {
962 return null;
963 }
964 PortStatistics portStats = portStatsMap.get(portNumber);
965 return portStats;
966 }
967
968 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200969 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
970 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
971 if (portStats == null) {
972 return Collections.emptyList();
973 }
974 return ImmutableList.copyOf(portStats.values());
975 }
976
977 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530978 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
979 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
980 if (portStatsMap == null) {
981 return null;
982 }
983 PortStatistics portStats = portStatsMap.get(portNumber);
984 return portStats;
985 }
986
987 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700988 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
989 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
990 return ports == null ? null : ports.get(portNumber);
991 }
992
993 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700994 public PortDescription getPortDescription(ProviderId pid,
995 DeviceId deviceId,
996 PortNumber portNumber) {
997 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
998 if (descs == null) {
999 return null;
1000 }
1001 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1002 final Optional<DeviceDescriptions> devDescs;
1003 synchronized (descs) {
1004 devDescs = Optional.ofNullable(descs.get(pid));
1005 }
1006 // DeviceDescriptions is concurrent access-safe
1007 return devDescs
1008 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1009 .map(Timestamped::value)
1010 .orElse(null);
1011 }
1012
1013 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001014 public boolean isAvailable(DeviceId deviceId) {
1015 return availableDevices.contains(deviceId);
1016 }
1017
1018 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001019 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001020 final NodeId myId = clusterService.getLocalNode().id();
1021 NodeId master = mastershipService.getMasterFor(deviceId);
1022
1023 // if there exist a master, forward
1024 // if there is no master, try to become one and process
1025
1026 boolean relinquishAtEnd = false;
1027 if (master == null) {
1028 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1029 if (myRole != MastershipRole.NONE) {
1030 relinquishAtEnd = true;
1031 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001032 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001033 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001034 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -07001035 if (term != null && myId.equals(term.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 &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -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);
1454 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001455 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001456 // remote offline timestamp suggests that the
1457 // device is off-line
1458 markOfflineInternal(deviceId, rOffline);
1459 }
1460
1461 Timestamp lOffline = offline.get(deviceId);
1462 if (lOffline != null && rOffline == null) {
1463 // locally offline, but remote is online, suggest offline
1464 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1465 }
1466
1467 // remove device offline Ad already processed
1468 offlineAds.remove(deviceId);
1469 } // end local device loop
1470 } // device lock
1471
1472 // If there is any Ads left, request them
1473 log.trace("Ads left {}, {}", devAds, portAds);
1474 reqDevices.addAll(devAds.keySet());
1475 reqPorts.addAll(portAds.keySet());
1476
1477 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1478 log.trace("Nothing to request to remote peer {}", sender);
1479 return;
1480 }
1481
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001482 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001483
1484 // 2-way Anti-Entropy for now
1485 try {
1486 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1487 } catch (IOException e) {
1488 log.error("Failed to send response advertisement to " + sender, e);
1489 }
1490
1491// Sketch of 3-way Anti-Entropy
1492// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1493// ClusterMessage message = new ClusterMessage(
1494// clusterService.getLocalNode().id(),
1495// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1496// SERIALIZER.encode(request));
1497//
1498// try {
1499// clusterCommunicator.unicast(message, advertisement.sender());
1500// } catch (IOException e) {
1501// log.error("Failed to send advertisement reply to "
1502// + advertisement.sender(), e);
1503// }
Madan Jampani47c93732014-10-06 20:46:08 -07001504 }
1505
Madan Jampani255a58b2014-10-09 12:08:20 -07001506 private void notifyDelegateIfNotNull(DeviceEvent event) {
1507 if (event != null) {
1508 notifyDelegate(event);
1509 }
1510 }
1511
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001512 private final class SendAdvertisementTask implements Runnable {
1513
1514 @Override
1515 public void run() {
1516 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001517 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001518 return;
1519 }
1520
1521 try {
1522 final NodeId self = clusterService.getLocalNode().id();
1523 Set<ControllerNode> nodes = clusterService.getNodes();
1524
1525 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1526 .transform(toNodeId())
1527 .toList();
1528
1529 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001530 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001531 return;
1532 }
1533
1534 NodeId peer;
1535 do {
1536 int idx = RandomUtils.nextInt(0, nodeIds.size());
1537 peer = nodeIds.get(idx);
1538 } while (peer.equals(self));
1539
1540 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1541
1542 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001543 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001544 return;
1545 }
1546
1547 try {
1548 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1549 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001550 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001551 return;
1552 }
1553 } catch (Exception e) {
1554 // catch all Exception to avoid Scheduled task being suppressed.
1555 log.error("Exception thrown while sending advertisement", e);
1556 }
1557 }
1558 }
1559
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001560 private void handleDeviceEvent(InternalDeviceEvent event) {
1561 ProviderId providerId = event.providerId();
1562 DeviceId deviceId = event.deviceId();
1563 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001564
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001565 try {
1566 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1567 deviceDescription));
1568 } catch (Exception e) {
1569 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001570 }
1571 }
1572
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001573 private void handleDeviceOfflineEvent(InternalDeviceOfflineEvent event) {
1574 DeviceId deviceId = event.deviceId();
1575 Timestamp timestamp = event.timestamp();
Madan Jampani25322532014-10-08 11:20:38 -07001576
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001577 try {
1578 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1579 } catch (Exception e) {
1580 log.warn("Exception thrown handling device offline", e);
Madan Jampani25322532014-10-08 11:20:38 -07001581 }
1582 }
1583
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001584 private void handleRemoveRequest(DeviceId did) {
1585 try {
1586 removeDevice(did);
1587 } 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}