blob: c72da5f16c586d205f7d75094fb2d77573d69570 [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 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);
Jordan Halterman8a0b3972017-08-15 16:14:18 -0700324 if (deviceEvent == null) {
325 return null;
326 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700327 mergedDesc = device.get(providerId).getDeviceDesc();
328 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800329
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700330 // If this node is the master for the device, update peers.
331 if (isMaster) {
Jordan Halterman8a0b3972017-08-15 16:14:18 -0700332 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
333 providerId, deviceId);
334 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800335 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700336 return null;
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700337 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800338
339 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700340 }
341
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700342 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700343 DeviceId deviceId,
344 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700345
346 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800347 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700348 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700349
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800350 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700351 // locking per device
352
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700353 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
354 log.debug("Ignoring outdated event: {}", deltaDesc);
355 return null;
356 }
357
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800358 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700359
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700360 final Device oldDevice = devices.get(deviceId);
361 final Device newDevice;
362
363 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700364 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700365 // on new device or valid update
366 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800367 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700368 } else {
369 // outdated event, ignored.
370 return null;
371 }
372 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700373 // REGISTER
374 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700375 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700376 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700377 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700378 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700379 } else {
380 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700381 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
382 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700383 }
384 }
385 }
386
387 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700388 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700389 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700390 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700391
392 // update composed device cache
393 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
394 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700395 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
396 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700397
398 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700399 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700400 }
401
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700402 log.debug("Device {} added", newDevice.id());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700403 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
404 }
405
406 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700407 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700408 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700409 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700410 Device newDevice, Timestamp newTimestamp,
411 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700412 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700413 boolean propertiesChanged =
414 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700415 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
mskala4b2081a2017-06-12 16:39:50 +0200416 !Objects.equals(oldDevice.providerId(), newDevice.providerId()) ||
417 !Objects.equals(oldDevice.chassisId(), newDevice.chassisId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700418 boolean annotationsChanged =
419 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700420
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700421 // Primary providers can respond to all changes, but ancillary ones
422 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800423 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700424 if ((providerId.isAncillary() && annotationsChanged) ||
425 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700426 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
427 if (!replaced) {
428 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700429 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800430 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700431 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700432
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700433 log.debug("Device {} updated", newDevice.id());
alshabibdc5d8bd2015-11-02 15:41:29 -0800434 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700435 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800436
helenyrwufd296b62016-06-22 17:43:02 -0700437 if (!providerId.isAncillary() && forceAvailable) {
alshabibdc5d8bd2015-11-02 15:41:29 -0800438 boolean wasOnline = availableDevices.contains(newDevice.id());
439 markOnline(newDevice.id(), newTimestamp);
440 if (!wasOnline) {
441 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
442 }
443 }
444 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700445 }
446
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700447 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700448 // update composed device cache
449 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
450 verify(oldDevice == null,
451 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
452 providerId, oldDevice, newDevice);
453
454 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700455 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700456 }
457
458 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
459 }
460
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700461 @Override
462 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700463 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
464 }
465
466 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700467 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700468 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700469 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700470 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800471 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700472 }
473 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700474 }
475
476 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700477 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700478 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700479
480 // locking device
481 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700482 // accept off-line if given timestamp is newer than
483 // the latest Timestamp from Primary provider
484 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
Thomas Vachuska4bd10b92016-12-15 10:13:38 -0800485 if (primDescs == null) {
486 return null;
487 }
488
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700489 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Saritha781984f2017-06-27 09:46:02 +0530490 if (lastTimestamp == null) {
491 lastTimestamp = deviceClockService.getTimestamp(deviceId);
492 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700493 if (timestamp.compareTo(lastTimestamp) <= 0) {
494 // outdated event ignore
495 return null;
496 }
497
498 offline.put(deviceId, timestamp);
499
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700500 Device device = devices.get(deviceId);
501 if (device == null) {
502 return null;
503 }
504 boolean removed = availableDevices.remove(deviceId);
505 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700506 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700507 }
508 return null;
509 }
510 }
511
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700512 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700513 public boolean markOnline(DeviceId deviceId) {
514 if (devices.containsKey(deviceId)) {
515 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
516 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
517 synchronized (deviceLock) {
518 if (markOnline(deviceId, timestamp)) {
519 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
520 return true;
521 } else {
522 return false;
523 }
524 }
525 }
526 log.warn("Device {} does not exist in store", deviceId);
527 return false;
528
529 }
530
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700531 /**
532 * Marks the device as available if the given timestamp is not outdated,
533 * compared to the time the device has been marked offline.
534 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700535 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700536 * @param timestamp of the event triggering this change.
537 * @return true if availability change request was accepted and changed the state
538 */
539 // Guarded by deviceDescs value (=Device lock)
540 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
541 // accept on-line if given timestamp is newer than
542 // the latest offline request Timestamp
543 Timestamp offlineTimestamp = offline.get(deviceId);
544 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700545 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700546
547 offline.remove(deviceId);
548 return availableDevices.add(deviceId);
549 }
550 return false;
551 }
552
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700553 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700554 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700555 DeviceId deviceId,
556 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700557
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800558 NodeId localNode = clusterService.getLocalNode().id();
559 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
560 // since it will trigger distributed store read.
561 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
562 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
563 // If we don't care much about topology performance, then it might be OK.
564 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700565
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800566 // Process port update only if we're the master of the device,
567 // otherwise signal the actual master.
568 List<DeviceEvent> deviceEvents = null;
569 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700570
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800571 final Timestamp newTimestamp;
572 try {
573 newTimestamp = deviceClockService.getTimestamp(deviceId);
574 } catch (IllegalStateException e) {
575 log.info("Timestamp was not available for device {}", deviceId);
576 log.debug(" discarding {}", portDescriptions);
577 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700578
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800579 // Possible situation:
580 // Device connected and became master for short period of time,
581 // but lost mastership before this instance had the chance to
582 // retrieve term information.
583
584 // Information dropped here is expected to be recoverable by
585 // device probing after mastership change
586
587 return Collections.emptyList();
588 }
589 log.debug("timestamp for {} {}", deviceId, newTimestamp);
590
591 final Timestamped<List<PortDescription>> timestampedInput
592 = new Timestamped<>(portDescriptions, newTimestamp);
593 final Timestamped<List<PortDescription>> merged;
594
595 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
596
597 synchronized (device) {
598 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
599 final DeviceDescriptions descs = device.get(providerId);
600 List<PortDescription> mergedList =
601 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700602 .transform(input ->
603 // lookup merged port description
604 descs.getPortDesc(input.portNumber()).value()
605 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700606 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800607 }
608
609 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700610 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700611 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800612 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
613 }
614
615 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700616 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700617 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700618
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800619 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700620 }
621
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700622 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700623 DeviceId deviceId,
624 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700625
626 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700627 if (device == null) {
628 log.debug("Device is no longer valid: {}", deviceId);
629 return Collections.emptyList();
630 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700631
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700632 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700633 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
634
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700635 List<DeviceEvent> events = new ArrayList<>();
636 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700637
638 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
639 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700640 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700641 }
642
643 DeviceDescriptions descs = descsMap.get(providerId);
644 // every provider must provide DeviceDescription.
645 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700646 "Device description for Device ID %s from Provider %s was not found",
647 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700648
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700649 Map<PortNumber, Port> ports = getPortMap(deviceId);
650
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700651 final Timestamp newTimestamp = portDescriptions.timestamp();
652
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700653 // Add new ports
654 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700655 for (PortDescription portDescription : portDescriptions.value()) {
656 final PortNumber number = portDescription.portNumber();
657 processed.add(number);
658
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700659 final Port oldPort = ports.get(number);
660 final Port newPort;
661
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700662
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700663 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
664 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700665 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700666 // on new port or valid update
667 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700668 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700669 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700670 newPort = composePort(device, number, descsMap);
671 } else {
672 // outdated event, ignored.
673 continue;
674 }
675
676 events.add(oldPort == null ?
677 createPort(device, newPort, ports) :
678 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700679 }
680
681 events.addAll(pruneOldPorts(device, ports, processed));
682 }
683 return FluentIterable.from(events).filter(notNull()).toList();
684 }
685
686 // Creates a new port based on the port description adds it to the map and
687 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700688 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700689 private DeviceEvent createPort(Device device, Port newPort,
690 Map<PortNumber, Port> ports) {
691 ports.put(newPort.number(), newPort);
692 return new DeviceEvent(PORT_ADDED, device, newPort);
693 }
694
695 // Checks if the specified port requires update and if so, it replaces the
696 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700697 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700698 private DeviceEvent updatePort(Device device, Port oldPort,
699 Port newPort,
700 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100701
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700702 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700703 oldPort.type() != newPort.type() ||
704 oldPort.portSpeed() != newPort.portSpeed() ||
705 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700706 ports.put(oldPort.number(), newPort);
707 return new DeviceEvent(PORT_UPDATED, device, newPort);
708 }
709 return null;
710 }
711
Michal Machce774332017-01-25 11:02:55 +0100712 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
713
714 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
715 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
716
717 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
718 }
719
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700720 // Prunes the specified list of ports based on which ports are in the
721 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700722 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700723 private List<DeviceEvent> pruneOldPorts(Device device,
724 Map<PortNumber, Port> ports,
725 Set<PortNumber> processed) {
726 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700727 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700728 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700729 Entry<PortNumber, Port> e = iterator.next();
730 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700731 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700732 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700733 iterator.remove();
734 }
735 }
736 return events;
737 }
738
739 // Gets the map of ports for the specified device; if one does not already
740 // exist, it creates and registers a new one.
741 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700742 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700743 }
744
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700745 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700746 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700747 Map<ProviderId, DeviceDescriptions> r;
748 r = deviceDescs.get(deviceId);
749 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700750 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700751 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
752 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
753 if (concurrentlyAdded != null) {
754 r = concurrentlyAdded;
755 }
756 }
757 return r;
758 }
759
760 // Guarded by deviceDescs value (=Device lock)
761 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
762 Map<ProviderId, DeviceDescriptions> device,
763 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700764 synchronized (device) {
765 DeviceDescriptions r = device.get(providerId);
766 if (r == null) {
767 r = new DeviceDescriptions(deltaDesc);
768 device.put(providerId, r);
769 }
770 return r;
771 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700772 }
773
774 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700775 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
776 DeviceId deviceId,
777 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700778 final Timestamp newTimestamp;
779 try {
780 newTimestamp = deviceClockService.getTimestamp(deviceId);
781 } catch (IllegalStateException e) {
782 log.info("Timestamp was not available for device {}", deviceId);
783 log.debug(" discarding {}", portDescription);
784 // Failed to generate timestamp. Ignoring.
785 // See updatePorts comment
786 return null;
787 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700788 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700789 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700790 final DeviceEvent event;
791 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800792 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
793 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700794 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800795 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700796 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700797 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700798 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700799 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700800 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800801 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700802 }
803 return event;
804 }
805
806 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700807 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700808 Device device = devices.get(deviceId);
809 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
810
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700811 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700812 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
813
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700814 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700815
816 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
817 log.debug("Ignoring outdated event: {}", deltaDesc);
818 return null;
819 }
820
821 DeviceDescriptions descs = descsMap.get(providerId);
822 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700823 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700824 "Device description for Device ID %s from Provider %s was not found",
825 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700826
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700827 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
828 final PortNumber number = deltaDesc.value().portNumber();
829 final Port oldPort = ports.get(number);
830 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700831 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100832 boolean toDelete = false;
833
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700834 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700835 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700836 // on new port or valid update
837 // update description
838 descs.putPortDesc(deltaDesc);
839 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100840 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700841 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700842 // same or outdated event, ignored.
843 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700844 return null;
845 }
846
847 if (oldPort == null) {
848 return createPort(device, newPort, ports);
849 } else {
Michal Machce774332017-01-25 11:02:55 +0100850 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700851 }
852 }
853 }
854
855 @Override
856 public List<Port> getPorts(DeviceId deviceId) {
857 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
858 if (ports == null) {
859 return Collections.emptyList();
860 }
861 return ImmutableList.copyOf(ports.values());
862 }
863
864 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700865 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
866 DeviceId deviceId) {
867 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
868 if (descs == null) {
869 return null;
870 }
871 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
872 final Optional<DeviceDescriptions> devDescs;
873 synchronized (descs) {
874 devDescs = Optional.ofNullable(descs.get(pid));
875 }
876 // DeviceDescriptions is concurrent access-safe
877 return devDescs
878 .map(dd -> dd.getPortDescs().values().stream()
879 .map(Timestamped::value))
880 .orElse(Stream.empty());
881 }
882
883 @Override
sangho538108b2015-04-08 14:29:20 -0700884 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200885 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700886
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200887 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
888 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
889 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
890
891 if (prvStatsMap != null) {
892 for (PortStatistics newStats : newStatsCollection) {
893 PortNumber port = PortNumber.portNumber(newStats.port());
894 PortStatistics prvStats = prvStatsMap.get(port);
895 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
896 PortStatistics deltaStats = builder.build();
897 if (prvStats != null) {
898 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
899 }
900 deltaStatsMap.put(port, deltaStats);
901 newStatsMap.put(port, newStats);
902 }
903 } else {
904 for (PortStatistics newStats : newStatsCollection) {
905 PortNumber port = PortNumber.portNumber(newStats.port());
906 newStatsMap.put(port, newStats);
907 }
sangho538108b2015-04-08 14:29:20 -0700908 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200909 devicePortDeltaStats.put(deviceId, deltaStatsMap);
910 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200911 // DeviceEvent returns null because of InternalPortStatsListener usage
912 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200913 }
914
915 /**
916 * Calculate delta statistics by subtracting previous from new statistics.
917 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700918 * @param deviceId device identifier
919 * @param prvStats previous port statistics
920 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200921 * @return PortStatistics
922 */
923 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
924 // calculate time difference
925 long deltaStatsSec, deltaStatsNano;
926 if (newStats.durationNano() < prvStats.durationNano()) {
927 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
928 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
929 } else {
930 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
931 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
932 }
933 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
934 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
935 .setPort(newStats.port())
936 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
937 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
938 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
939 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
940 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
941 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
942 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
943 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
944 .setDurationSec(deltaStatsSec)
945 .setDurationNano(deltaStatsNano)
946 .build();
947 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700948 }
949
950 @Override
951 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700952 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
953 if (portStats == null) {
954 return Collections.emptyList();
955 }
956 return ImmutableList.copyOf(portStats.values());
957 }
958
959 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530960 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
961 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
962 if (portStatsMap == null) {
963 return null;
964 }
965 PortStatistics portStats = portStatsMap.get(portNumber);
966 return portStats;
967 }
968
969 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200970 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
971 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
972 if (portStats == null) {
973 return Collections.emptyList();
974 }
975 return ImmutableList.copyOf(portStats.values());
976 }
977
978 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530979 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
980 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
981 if (portStatsMap == null) {
982 return null;
983 }
984 PortStatistics portStats = portStatsMap.get(portNumber);
985 return portStats;
986 }
987
988 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700989 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
990 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
991 return ports == null ? null : ports.get(portNumber);
992 }
993
994 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700995 public PortDescription getPortDescription(ProviderId pid,
996 DeviceId deviceId,
997 PortNumber portNumber) {
998 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
999 if (descs == null) {
1000 return null;
1001 }
1002 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1003 final Optional<DeviceDescriptions> devDescs;
1004 synchronized (descs) {
1005 devDescs = Optional.ofNullable(descs.get(pid));
1006 }
1007 // DeviceDescriptions is concurrent access-safe
1008 return devDescs
1009 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1010 .map(Timestamped::value)
1011 .orElse(null);
1012 }
1013
1014 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001015 public boolean isAvailable(DeviceId deviceId) {
1016 return availableDevices.contains(deviceId);
1017 }
1018
1019 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001020 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001021 final NodeId myId = clusterService.getLocalNode().id();
1022 NodeId master = mastershipService.getMasterFor(deviceId);
1023
1024 // if there exist a master, forward
1025 // if there is no master, try to become one and process
1026
1027 boolean relinquishAtEnd = false;
1028 if (master == null) {
1029 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1030 if (myRole != MastershipRole.NONE) {
1031 relinquishAtEnd = true;
1032 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001033 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001034 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001035 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -07001036 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001037 master = myId;
1038 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001039 }
1040
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001041 boolean isMaster = myId.equals(master);
1042
1043 // If this node is not the master, forward the request.
1044 if (!isMaster) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001045 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001046 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001047
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001048 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001049 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001050 /* error log:
1051 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1052 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001053 }
1054
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001055 // If this node is the master, get a timestamp. Otherwise, default to the current device timestamp.
1056 Timestamp timestamp = isMaster ? deviceClockService.getTimestamp(deviceId) : null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001057
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001058 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001059
1060 // If this node is the master, update peers.
1061 if (isMaster && event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001062 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001063 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001064 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001065 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001066
1067 // Relinquish mastership if acquired to remove the device.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001068 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001069 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001070 mastershipService.relinquishMastership(deviceId);
1071 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001072 return event;
1073 }
1074
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001075 private DeviceEvent removeDeviceInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001076
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001077 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001078 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001079 // accept removal request if given timestamp is newer than
1080 // the latest Timestamp from Primary provider
1081 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001082 if (primDescs == null) {
1083 return null;
1084 }
1085
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001086 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001087
1088 // If no timestamp is set, default the timestamp to the last timestamp for the device.
1089 if (timestamp == null) {
1090 timestamp = lastTimestamp;
1091 }
1092
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001093 if (timestamp.compareTo(lastTimestamp) <= 0) {
1094 // outdated event ignore
1095 return null;
1096 }
1097 removalRequest.put(deviceId, timestamp);
1098
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001099 Device device = devices.remove(deviceId);
1100 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001101 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1102 if (ports != null) {
1103 ports.clear();
1104 }
1105 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001106 descs.clear();
1107 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001108 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001109 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001110 }
1111
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001112 /**
1113 * Checks if given timestamp is superseded by removal request
1114 * with more recent timestamp.
1115 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001116 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001117 * @param timestampToCheck timestamp of an event to check
1118 * @return true if device is already removed
1119 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001120 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1121 Timestamp removalTimestamp = removalRequest.get(deviceId);
1122 if (removalTimestamp != null &&
Jordan Halterman8a0b3972017-08-15 16:14:18 -07001123 removalTimestamp.compareTo(timestampToCheck) > 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001124 // removalRequest is more recent
1125 return true;
1126 }
1127 return false;
1128 }
1129
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001130 /**
1131 * Returns a Device, merging description given from multiple Providers.
1132 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001133 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001134 * @param providerDescs Collection of Descriptions from multiple providers
1135 * @return Device instance
1136 */
1137 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001138 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001139
Thomas Vachuska444eda62014-10-28 13:09:42 -07001140 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001141
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001142 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001143
1144 DeviceDescriptions desc = providerDescs.get(primary);
1145
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001146 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001147 Type type = base.type();
1148 String manufacturer = base.manufacturer();
1149 String hwVersion = base.hwVersion();
1150 String swVersion = base.swVersion();
1151 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001152 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001153 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1154 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001155
1156 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1157 if (e.getKey().equals(primary)) {
1158 continue;
1159 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001160 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001161 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001162 // Currently assuming there will never be a key conflict between
1163 // providers
1164
1165 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001166 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001167 }
1168
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001169 return new DefaultDevice(primary, deviceId, type, manufacturer,
1170 hwVersion, swVersion, serialNumber,
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001171 chassisId, annotations.build());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001172 }
1173
Marc De Leenheer88194c32015-05-29 22:10:59 -07001174 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1175 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001176 return new DefaultPort(device, number, isEnabled, description.type(),
1177 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001178 }
1179
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001180 /**
1181 * Returns a Port, merging description given from multiple Providers.
1182 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001183 * @param device device the port is on
1184 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001185 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001186 * @return Port instance
1187 */
1188 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001189 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001190
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001191 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001192 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001193 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001194 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001195 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001196 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001197 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1198 if (portDesc != null) {
1199 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001200 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001201 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001202 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001203 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001204 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001205 if (e.getKey().equals(primary)) {
1206 continue;
1207 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001208 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001209 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001210 // Currently assuming there will never be a key conflict between
1211 // providers
1212
1213 // annotation merging. not so efficient, should revisit later
1214 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1215 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001216 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1217 continue;
1218 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001219 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001220 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001221 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001222 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001223 }
1224 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001225 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001226 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001227 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001228 PortDescription current = portDesc.value();
1229 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001230 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001231 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001232 }
1233
1234 /**
1235 * @return primary ProviderID, or randomly chosen one if none exists
1236 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001237 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001238 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001239 ProviderId fallBackPrimary = null;
1240 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1241 if (!e.getKey().isAncillary()) {
1242 return e.getKey();
1243 } else if (fallBackPrimary == null) {
1244 // pick randomly as a fallback in case there is no primary
1245 fallBackPrimary = e.getKey();
1246 }
1247 }
1248 return fallBackPrimary;
1249 }
1250
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001251 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001252 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001253 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001254 return providerDescs.get(pid);
1255 }
1256
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001257 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001258 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001259 }
1260
Jonathan Hart7d656f42015-01-27 14:07:23 -08001261 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001262 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001263 }
Madan Jampani47c93732014-10-06 20:46:08 -07001264
Jonathan Hart7d656f42015-01-27 14:07:23 -08001265 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001266 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001267 }
1268
Jonathan Hart7d656f42015-01-27 14:07:23 -08001269 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001270 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001271 }
1272
Jonathan Hart7d656f42015-01-27 14:07:23 -08001273 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001274 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001275 }
1276
Jonathan Hart7d656f42015-01-27 14:07:23 -08001277 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001278 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001279 }
1280
Jonathan Hart7d656f42015-01-27 14:07:23 -08001281 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001282 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1283 }
1284
1285 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1286 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001287 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001288 } catch (IOException e) {
1289 log.error("Failed to send" + event + " to " + recipient, e);
1290 }
1291 }
1292
1293 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1294 try {
1295 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1296 } catch (IOException e) {
1297 log.error("Failed to send" + event + " to " + recipient, e);
1298 }
1299 }
1300
1301 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1302 try {
1303 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1304 } catch (IOException e) {
1305 log.error("Failed to send" + event + " to " + recipient, e);
1306 }
1307 }
1308
1309 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1310 try {
1311 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1312 } catch (IOException e) {
1313 log.error("Failed to send" + event + " to " + recipient, e);
1314 }
1315 }
1316
1317 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1318 try {
1319 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1320 } catch (IOException e) {
1321 log.error("Failed to send" + event + " to " + recipient, e);
1322 }
1323 }
1324
1325 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1326 final NodeId self = clusterService.getLocalNode().id();
1327
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001328 final int numDevices = deviceDescs.size();
1329 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1330 final int portsPerDevice = 8; // random factor to minimize reallocation
1331 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1332 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001333
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001334 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001335
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001336 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001337 synchronized (devDescs) {
1338
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001339 // send device offline timestamp
1340 Timestamp lOffline = this.offline.get(deviceId);
1341 if (lOffline != null) {
1342 adOffline.put(deviceId, lOffline);
1343 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001344
1345 for (Entry<ProviderId, DeviceDescriptions>
1346 prov : devDescs.entrySet()) {
1347
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001348 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001349 final ProviderId provId = prov.getKey();
1350 final DeviceDescriptions descs = prov.getValue();
1351
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001352 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001353 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001354
1355 for (Entry<PortNumber, Timestamped<PortDescription>>
1356 portDesc : descs.getPortDescs().entrySet()) {
1357
1358 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001359 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001360 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001361 }
1362 }
1363 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001364 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001365
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001366 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001367 }
1368
1369 /**
1370 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001371 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001372 * Notify sender about out-dated information using regular replication message.
1373 * Send back advertisement to sender if not in sync.
1374 *
1375 * @param advertisement to respond to
1376 */
1377 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1378
1379 final NodeId sender = advertisement.sender();
1380
1381 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1382 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1383 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1384
1385 // Fragments to request
1386 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1387 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1388
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001389 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001390 final DeviceId deviceId = de.getKey();
1391 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1392
1393 synchronized (lDevice) {
1394 // latestTimestamp across provider
1395 // Note: can be null initially
1396 Timestamp localLatest = offline.get(deviceId);
1397
1398 // handle device Ads
1399 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1400 final ProviderId provId = prov.getKey();
1401 final DeviceDescriptions lDeviceDescs = prov.getValue();
1402
1403 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1404
1405
1406 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1407 Timestamp advDevTimestamp = devAds.get(devFragId);
1408
Jonathan Hart403ea932015-02-20 16:23:00 -08001409 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1410 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001411 // remote does not have it or outdated, suggest
1412 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1413 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1414 // local is outdated, request
1415 reqDevices.add(devFragId);
1416 }
1417
1418 // handle port Ads
1419 for (Entry<PortNumber, Timestamped<PortDescription>>
1420 pe : lDeviceDescs.getPortDescs().entrySet()) {
1421
1422 final PortNumber num = pe.getKey();
1423 final Timestamped<PortDescription> lPort = pe.getValue();
1424
1425 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1426
1427 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001428 if (advPortTimestamp == null || lPort.isNewerThan(
1429 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001430 // remote does not have it or outdated, suggest
1431 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1432 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1433 // local is outdated, request
1434 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1435 reqPorts.add(portFragId);
1436 }
1437
1438 // remove port Ad already processed
1439 portAds.remove(portFragId);
1440 } // end local port loop
1441
1442 // remove device Ad already processed
1443 devAds.remove(devFragId);
1444
1445 // find latest and update
1446 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1447 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001448 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001449 localLatest = providerLatest;
1450 }
1451 } // end local provider loop
1452
1453 // checking if remote timestamp is more recent.
1454 Timestamp rOffline = offlineAds.get(deviceId);
1455 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001456 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001457 // remote offline timestamp suggests that the
1458 // device is off-line
1459 markOfflineInternal(deviceId, rOffline);
1460 }
1461
1462 Timestamp lOffline = offline.get(deviceId);
1463 if (lOffline != null && rOffline == null) {
1464 // locally offline, but remote is online, suggest offline
1465 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1466 }
1467
1468 // remove device offline Ad already processed
1469 offlineAds.remove(deviceId);
1470 } // end local device loop
1471 } // device lock
1472
1473 // If there is any Ads left, request them
1474 log.trace("Ads left {}, {}", devAds, portAds);
1475 reqDevices.addAll(devAds.keySet());
1476 reqPorts.addAll(portAds.keySet());
1477
1478 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1479 log.trace("Nothing to request to remote peer {}", sender);
1480 return;
1481 }
1482
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001483 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001484
1485 // 2-way Anti-Entropy for now
1486 try {
1487 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1488 } catch (IOException e) {
1489 log.error("Failed to send response advertisement to " + sender, e);
1490 }
1491
1492// Sketch of 3-way Anti-Entropy
1493// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1494// ClusterMessage message = new ClusterMessage(
1495// clusterService.getLocalNode().id(),
1496// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1497// SERIALIZER.encode(request));
1498//
1499// try {
1500// clusterCommunicator.unicast(message, advertisement.sender());
1501// } catch (IOException e) {
1502// log.error("Failed to send advertisement reply to "
1503// + advertisement.sender(), e);
1504// }
Madan Jampani47c93732014-10-06 20:46:08 -07001505 }
1506
Madan Jampani255a58b2014-10-09 12:08:20 -07001507 private void notifyDelegateIfNotNull(DeviceEvent event) {
1508 if (event != null) {
1509 notifyDelegate(event);
1510 }
1511 }
1512
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001513 private final class SendAdvertisementTask implements Runnable {
1514
1515 @Override
1516 public void run() {
1517 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001518 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001519 return;
1520 }
1521
1522 try {
1523 final NodeId self = clusterService.getLocalNode().id();
1524 Set<ControllerNode> nodes = clusterService.getNodes();
1525
1526 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1527 .transform(toNodeId())
1528 .toList();
1529
1530 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001531 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001532 return;
1533 }
1534
1535 NodeId peer;
1536 do {
1537 int idx = RandomUtils.nextInt(0, nodeIds.size());
1538 peer = nodeIds.get(idx);
1539 } while (peer.equals(self));
1540
1541 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1542
1543 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001544 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001545 return;
1546 }
1547
1548 try {
1549 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1550 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001551 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001552 return;
1553 }
1554 } catch (Exception e) {
1555 // catch all Exception to avoid Scheduled task being suppressed.
1556 log.error("Exception thrown while sending advertisement", e);
1557 }
1558 }
1559 }
1560
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001561 private void handleDeviceEvent(InternalDeviceEvent event) {
1562 ProviderId providerId = event.providerId();
1563 DeviceId deviceId = event.deviceId();
1564 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001565
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001566 try {
1567 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1568 deviceDescription));
1569 } catch (Exception e) {
1570 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001571 }
1572 }
1573
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001574 private void handleDeviceOfflineEvent(InternalDeviceOfflineEvent event) {
1575 DeviceId deviceId = event.deviceId();
1576 Timestamp timestamp = event.timestamp();
Madan Jampani25322532014-10-08 11:20:38 -07001577
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001578 try {
1579 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1580 } catch (Exception e) {
1581 log.warn("Exception thrown handling device offline", e);
Madan Jampani25322532014-10-08 11:20:38 -07001582 }
1583 }
1584
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001585 private void handleRemoveRequest(DeviceId did) {
1586 try {
Jayasree Ghosh7d96d6a2017-02-27 18:35:32 +05301587 DeviceEvent event = removeDevice(did);
1588 notifyDelegateIfNotNull(event);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001589 } catch (Exception e) {
1590 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001591 }
1592 }
1593
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001594 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1595 DeviceId deviceId = event.deviceId();
1596 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001597
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001598 try {
1599 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1600 } catch (Exception e) {
1601 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001602 }
1603 }
1604
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001605 private void handlePortEvent(InternalPortEvent event) {
1606 ProviderId providerId = event.providerId();
1607 DeviceId deviceId = event.deviceId();
1608 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001609
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001610 if (getDevice(deviceId) == null) {
1611 log.debug("{} not found on this node yet, ignoring.", deviceId);
1612 // Note: dropped information will be recovered by anti-entropy
1613 return;
1614 }
Madan Jampani47c93732014-10-06 20:46:08 -07001615
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001616 try {
1617 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1618 } catch (Exception e) {
1619 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001620 }
1621 }
1622
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001623 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1624 ProviderId providerId = event.providerId();
1625 DeviceId deviceId = event.deviceId();
1626 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001627
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001628 if (getDevice(deviceId) == null) {
1629 log.debug("{} not found on this node yet, ignoring.", deviceId);
1630 // Note: dropped information will be recovered by anti-entropy
1631 return;
1632 }
Madan Jampani47c93732014-10-06 20:46:08 -07001633
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001634 try {
1635 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1636 } catch (Exception e) {
1637 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001638 }
1639 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001640
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001641 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1642 try {
1643 handleAdvertisement(advertisement);
1644 } catch (Exception e) {
1645 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001646 }
1647 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001648
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001649 private class InternalPortStatsListener
1650 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1651 @Override
1652 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1653 if (event.type() == PUT) {
1654 Device device = devices.get(event.key());
1655 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001656 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001657 }
1658 }
1659 }
1660 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001661}