blob: 7f593e769b88afa7c4825b911aad0715bd1ec468 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2014-present Open Networking Foundation
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.store.device.impl;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070017
Ray Milkey2bf5ea72017-06-01 09:03:34 -070018import java.io.IOException;
19import java.util.ArrayList;
20import java.util.Collection;
21import java.util.Collections;
22import java.util.HashMap;
23import java.util.HashSet;
24import java.util.Iterator;
25import java.util.List;
26import java.util.Map;
27import java.util.Map.Entry;
28import java.util.Objects;
29import java.util.Optional;
30import java.util.Set;
31import java.util.concurrent.ConcurrentHashMap;
32import java.util.concurrent.ConcurrentMap;
33import java.util.concurrent.ExecutorService;
34import java.util.concurrent.ScheduledExecutorService;
35import java.util.concurrent.TimeUnit;
36import java.util.function.Consumer;
37import java.util.stream.Stream;
38
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070039import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070040import org.apache.felix.scr.annotations.Activate;
41import org.apache.felix.scr.annotations.Component;
42import org.apache.felix.scr.annotations.Deactivate;
43import org.apache.felix.scr.annotations.Reference;
44import org.apache.felix.scr.annotations.ReferenceCardinality;
45import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080046import org.onlab.packet.ChassisId;
47import org.onlab.util.KryoNamespace;
Brian O'Connorabafb502014-12-02 22:26:20 -080048import org.onosproject.cluster.ClusterService;
49import org.onosproject.cluster.ControllerNode;
50import org.onosproject.cluster.NodeId;
51import org.onosproject.mastership.MastershipService;
Brian O'Connorabafb502014-12-02 22:26:20 -080052import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070053import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080054import org.onosproject.net.AnnotationsUtil;
55import org.onosproject.net.DefaultAnnotations;
56import org.onosproject.net.DefaultDevice;
57import org.onosproject.net.DefaultPort;
58import org.onosproject.net.Device;
59import org.onosproject.net.Device.Type;
60import org.onosproject.net.DeviceId;
61import org.onosproject.net.MastershipRole;
62import org.onosproject.net.Port;
63import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070064import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080065import org.onosproject.net.device.DeviceClockService;
66import org.onosproject.net.device.DeviceDescription;
67import org.onosproject.net.device.DeviceEvent;
68import org.onosproject.net.device.DeviceStore;
69import org.onosproject.net.device.DeviceStoreDelegate;
70import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070071import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080072import org.onosproject.net.provider.ProviderId;
73import org.onosproject.store.AbstractStore;
74import org.onosproject.store.Timestamp;
75import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
Brian O'Connorabafb502014-12-02 22:26:20 -080076import org.onosproject.store.cluster.messaging.MessageSubject;
Jordan Haltermanebedbb52017-08-08 15:57:50 -070077import org.onosproject.store.impl.MastershipBasedTimestamp;
Brian O'Connorabafb502014-12-02 22:26:20 -080078import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070079import org.onosproject.store.serializers.KryoNamespaces;
Brian O'Connor6de2e202015-05-21 14:30:41 -070080import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070081import org.onosproject.store.service.EventuallyConsistentMap;
82import org.onosproject.store.service.EventuallyConsistentMapEvent;
83import org.onosproject.store.service.EventuallyConsistentMapListener;
84import org.onosproject.store.service.MultiValuedTimestamp;
Jordan Halterman2c83a102017-08-20 17:11:41 -070085import org.onosproject.store.service.Serializer;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070086import org.onosproject.store.service.StorageService;
87import org.onosproject.store.service.WallClockTimestamp;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070088import org.slf4j.Logger;
89
Ray Milkey2bf5ea72017-06-01 09:03:34 -070090import com.google.common.collect.FluentIterable;
91import com.google.common.collect.ImmutableList;
92import com.google.common.collect.Maps;
93import com.google.common.collect.Sets;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070094
95import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070096import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070097import static com.google.common.base.Verify.verify;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -080098import static java.util.concurrent.Executors.newCachedThreadPool;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080099import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800100import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800101import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800102import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
Ray Milkey9ef22232016-07-14 12:42:37 -0700103import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED;
104import static org.onosproject.net.device.DeviceEvent.Type.PORT_ADDED;
105import static org.onosproject.net.device.DeviceEvent.Type.PORT_REMOVED;
106import static org.onosproject.net.device.DeviceEvent.Type.PORT_STATS_UPDATED;
107import static org.onosproject.net.device.DeviceEvent.Type.PORT_UPDATED;
108import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700109import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE;
110import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVED;
Ray Milkey9ef22232016-07-14 12:42:37 -0700111import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700112import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_UPDATE;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700113import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE;
114import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_UPDATE;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700115import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800116import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700117
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700118/**
119 * Manages inventory of infrastructure devices using gossip protocol to distribute
120 * information.
121 */
122@Component(immediate = true)
123@Service
124public class GossipDeviceStore
125 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
126 implements DeviceStore {
127
128 private final Logger log = getLogger(getClass());
129
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700130 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800131 // Timeout in milliseconds to process device or ports on remote master node
132 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700133
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700134 // innerMap is used to lock a Device, thus instance should never be replaced.
135 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700136 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700137 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700138
139 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700140 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
141 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700142
143 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200144 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700145 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
146 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700147
148 // to be updated under Device lock
149 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
150 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700151
152 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700153 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700154
155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700156 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700157
Madan Jampani47c93732014-10-06 20:46:08 -0700158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700159 protected StorageService storageService;
160
161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700162 protected ClusterCommunicationService clusterCommunicator;
163
Madan Jampani53e44e62014-10-07 12:39:51 -0700164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
165 protected ClusterService clusterService;
166
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
168 protected MastershipService mastershipService;
169
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800170 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
171 protected MastershipTermService termService;
172
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700173 private static final Timestamp DEFAULT_TIMESTAMP = new MastershipBasedTimestamp(0, 0);
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800174
Jordan Halterman2c83a102017-08-20 17:11:41 -0700175 protected static final Serializer SERIALIZER = Serializer.using(KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800176 .register(DistributedStoreSerializers.STORE_COMMON)
177 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
178 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
179 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700180 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800181 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
182 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700183 .register(DeviceAntiEntropyAdvertisement.class)
184 .register(DeviceFragmentId.class)
185 .register(PortFragmentId.class)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700186 .build("GossipDevice"));
Madan Jampani53e44e62014-10-07 12:39:51 -0700187
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800188 private ExecutorService executor;
189
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800190 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700191
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800192 // TODO make these anti-entropy parameters configurable
193 private long initialDelaySec = 5;
194 private long periodSec = 5;
195
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700196 @Activate
197 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800198 executor = newCachedThreadPool(groupedThreads("onos/device", "fg-%d", log));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800199
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800200 backgroundExecutor =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800201 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d", log)));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700202
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700203 addSubscriber(DEVICE_UPDATE, this::handleDeviceEvent);
204 addSubscriber(DEVICE_OFFLINE, this::handleDeviceOfflineEvent);
205 addSubscriber(DEVICE_REMOVE_REQ, this::handleRemoveRequest);
206 addSubscriber(DEVICE_REMOVED, this::handleDeviceRemovedEvent);
207 addSubscriber(PORT_UPDATE, this::handlePortEvent);
208 addSubscriber(PORT_STATUS_UPDATE, this::handlePortStatusEvent);
209 addSubscriber(DEVICE_ADVERTISE, this::handleDeviceAdvertisement);
Madan Jampani2af244a2015-02-22 13:12:01 -0800210
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700211 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800212 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700213 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700214
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700215 // Create a distributed map for port stats.
216 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
217 .register(KryoNamespaces.API)
HIGUCHI Yuta03666a32016-05-18 11:49:09 -0700218 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
219 .register(MultiValuedTimestamp.class);
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700220
221 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
222 .withName("port-stats")
223 .withSerializer(deviceDataSerializer)
224 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700225 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700226 .withTombstonesDisabled()
227 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200228 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
229 eventuallyConsistentMapBuilder()
230 .withName("port-stats-delta")
231 .withSerializer(deviceDataSerializer)
232 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
233 .withTimestampProvider((k, v) -> new WallClockTimestamp())
234 .withTombstonesDisabled()
235 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700236 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700237 log.info("Started");
238 }
239
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700240 private <M> void addSubscriber(MessageSubject subject, Consumer<M> handler) {
241 clusterCommunicator.addSubscriber(subject, SERIALIZER::decode, handler, executor);
242 }
243
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700244 @Deactivate
245 public void deactivate() {
Frank Wange0eb5ce2016-07-01 18:21:25 +0800246 devicePortStats.removeListener(portStatsListener);
Madan Jampani632f16b2015-08-11 12:42:59 -0700247 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200248 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800249 executor.shutdownNow();
250
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800251 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700252 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800253 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700254 log.error("Timeout during executor shutdown");
255 }
256 } catch (InterruptedException e) {
257 log.error("Error during executor shutdown", e);
Ray Milkey5c7d4882018-02-05 14:50:39 -0800258 Thread.currentThread().interrupt();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700259 }
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 Haltermanf9f55632017-12-19 14:56:08 -0800307 boolean isMaster = localNode.equals(deviceNode);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800308
309 // Process device update only if we're the master,
310 // otherwise signal the actual master.
311 DeviceEvent deviceEvent = null;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800312
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700313 // If this node is the master for the device, acquire a new timestamp. Otherwise,
314 // use a 0,0 or tombstone timestamp to create the device if it doesn't already exist.
Jordan Haltermanf9f55632017-12-19 14:56:08 -0800315 Timestamp newTimestamp;
316 try {
317 newTimestamp = isMaster
318 ? deviceClockService.getTimestamp(deviceId)
319 : removalRequest.getOrDefault(deviceId, DEFAULT_TIMESTAMP);
320 } catch (IllegalStateException e) {
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -0800321 newTimestamp = removalRequest.getOrDefault(deviceId, DEFAULT_TIMESTAMP);
Jordan Haltermanf9f55632017-12-19 14:56:08 -0800322 isMaster = false;
323 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700324 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
325 final Timestamped<DeviceDescription> mergedDesc;
326 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800327
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700328 synchronized (device) {
329 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
Jordan Halterman8a0b3972017-08-15 16:14:18 -0700330 if (deviceEvent == null) {
331 return null;
332 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700333 mergedDesc = device.get(providerId).getDeviceDesc();
334 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800335
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700336 // If this node is the master for the device, update peers.
337 if (isMaster) {
Jordan Halterman8a0b3972017-08-15 16:14:18 -0700338 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
339 providerId, deviceId);
340 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700341 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800342
343 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700344 }
345
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700346 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700347 DeviceId deviceId,
348 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700349
350 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800351 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700352 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700353
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800354 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700355 // locking per device
356
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700357 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
358 log.debug("Ignoring outdated event: {}", deltaDesc);
359 return null;
360 }
361
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800362 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700363
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700364 final Device oldDevice = devices.get(deviceId);
365 final Device newDevice;
366
367 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700368 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700369 // on new device or valid update
370 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800371 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700372 } else {
373 // outdated event, ignored.
374 return null;
375 }
376 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700377 // REGISTER
378 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700379 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700380 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700381 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700382 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700383 } else {
384 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700385 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
386 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700387 }
388 }
389 }
390
391 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700392 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700393 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700394 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700395
396 // update composed device cache
397 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
398 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700399 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
400 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700401
402 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700403 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700404 }
405
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700406 log.debug("Device {} added", newDevice.id());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700407 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
408 }
409
410 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700411 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700412 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700413 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700414 Device newDevice, Timestamp newTimestamp,
415 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700416 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700417 boolean propertiesChanged =
418 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700419 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
mskala4b2081a2017-06-12 16:39:50 +0200420 !Objects.equals(oldDevice.providerId(), newDevice.providerId()) ||
421 !Objects.equals(oldDevice.chassisId(), newDevice.chassisId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700422 boolean annotationsChanged =
423 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700424
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700425 // Primary providers can respond to all changes, but ancillary ones
426 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800427 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700428 if ((providerId.isAncillary() && annotationsChanged) ||
429 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700430 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
431 if (!replaced) {
432 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700433 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800434 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700435 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700436
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700437 log.debug("Device {} updated", newDevice.id());
alshabibdc5d8bd2015-11-02 15:41:29 -0800438 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700439 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800440
helenyrwufd296b62016-06-22 17:43:02 -0700441 if (!providerId.isAncillary() && forceAvailable) {
alshabibdc5d8bd2015-11-02 15:41:29 -0800442 boolean wasOnline = availableDevices.contains(newDevice.id());
443 markOnline(newDevice.id(), newTimestamp);
444 if (!wasOnline) {
445 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
446 }
447 }
448 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700449 }
450
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700451 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700452 // update composed device cache
453 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
454 verify(oldDevice == null,
455 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
456 providerId, oldDevice, newDevice);
457
458 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700459 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700460 }
461
462 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
463 }
464
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700465 @Override
466 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700467 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
468 }
469
470 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700471 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700472 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700473 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700474 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800475 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700476 }
477 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700478 }
479
480 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700481 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700482 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700483
484 // locking device
485 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700486 // accept off-line if given timestamp is newer than
487 // the latest Timestamp from Primary provider
488 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
jaegonkim73c21bd2018-01-13 10:52:02 +0900489 if (primDescs != null) {
490 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
491 if (lastTimestamp == null) {
492 lastTimestamp = deviceClockService.getTimestamp(deviceId);
493 }
494 if (timestamp.compareTo(lastTimestamp) <= 0) {
495 // outdated event ignore
496 return null;
497 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700498 }
499
500 offline.put(deviceId, timestamp);
501
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700502 Device device = devices.get(deviceId);
503 if (device == null) {
504 return null;
505 }
506 boolean removed = availableDevices.remove(deviceId);
507 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700508 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700509 }
510 return null;
511 }
512 }
513
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700514 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700515 public boolean markOnline(DeviceId deviceId) {
516 if (devices.containsKey(deviceId)) {
517 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
518 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
519 synchronized (deviceLock) {
520 if (markOnline(deviceId, timestamp)) {
521 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
522 return true;
523 } else {
524 return false;
525 }
526 }
527 }
528 log.warn("Device {} does not exist in store", deviceId);
529 return false;
530
531 }
532
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700533 /**
534 * Marks the device as available if the given timestamp is not outdated,
535 * compared to the time the device has been marked offline.
536 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700537 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700538 * @param timestamp of the event triggering this change.
539 * @return true if availability change request was accepted and changed the state
540 */
541 // Guarded by deviceDescs value (=Device lock)
542 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
543 // accept on-line if given timestamp is newer than
544 // the latest offline request Timestamp
545 Timestamp offlineTimestamp = offline.get(deviceId);
546 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700547 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700548
549 offline.remove(deviceId);
550 return availableDevices.add(deviceId);
551 }
552 return false;
553 }
554
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700555 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700556 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700557 DeviceId deviceId,
558 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700559
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800560 NodeId localNode = clusterService.getLocalNode().id();
561 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
562 // since it will trigger distributed store read.
563 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
564 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
565 // If we don't care much about topology performance, then it might be OK.
566 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700567
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800568 // Process port update only if we're the master of the device,
569 // otherwise signal the actual master.
570 List<DeviceEvent> deviceEvents = null;
571 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700572
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800573 final Timestamp newTimestamp;
574 try {
575 newTimestamp = deviceClockService.getTimestamp(deviceId);
576 } catch (IllegalStateException e) {
577 log.info("Timestamp was not available for device {}", deviceId);
578 log.debug(" discarding {}", portDescriptions);
579 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700580
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800581 // Possible situation:
582 // Device connected and became master for short period of time,
583 // but lost mastership before this instance had the chance to
584 // retrieve term information.
585
586 // Information dropped here is expected to be recoverable by
587 // device probing after mastership change
588
589 return Collections.emptyList();
590 }
591 log.debug("timestamp for {} {}", deviceId, newTimestamp);
592
593 final Timestamped<List<PortDescription>> timestampedInput
594 = new Timestamped<>(portDescriptions, newTimestamp);
595 final Timestamped<List<PortDescription>> merged;
596
597 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
598
599 synchronized (device) {
600 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
601 final DeviceDescriptions descs = device.get(providerId);
602 List<PortDescription> mergedList =
603 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700604 .transform(input ->
605 // lookup merged port description
606 descs.getPortDesc(input.portNumber()).value()
607 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700608 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800609 }
610
611 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700612 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700613 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800614 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
615 }
616
617 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700618 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700619 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700620
Ray Milkeyfe0e0852018-01-18 11:14:05 -0800621 return deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700622 }
623
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700624 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700625 DeviceId deviceId,
626 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700627
628 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700629 if (device == null) {
630 log.debug("Device is no longer valid: {}", deviceId);
631 return Collections.emptyList();
632 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700633
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700634 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700635 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
636
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700637 List<DeviceEvent> events = new ArrayList<>();
638 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700639
640 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
641 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700642 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700643 }
644
645 DeviceDescriptions descs = descsMap.get(providerId);
646 // every provider must provide DeviceDescription.
647 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700648 "Device description for Device ID %s from Provider %s was not found",
649 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700650
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700651 Map<PortNumber, Port> ports = getPortMap(deviceId);
652
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700653 final Timestamp newTimestamp = portDescriptions.timestamp();
654
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700655 // Add new ports
656 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700657 for (PortDescription portDescription : portDescriptions.value()) {
658 final PortNumber number = portDescription.portNumber();
659 processed.add(number);
660
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700661 final Port oldPort = ports.get(number);
662 final Port newPort;
663
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700664
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700665 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
666 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700667 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700668 // on new port or valid update
669 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700670 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700671 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700672 newPort = composePort(device, number, descsMap);
673 } else {
674 // outdated event, ignored.
675 continue;
676 }
677
678 events.add(oldPort == null ?
679 createPort(device, newPort, ports) :
680 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700681 }
682
683 events.addAll(pruneOldPorts(device, ports, processed));
684 }
685 return FluentIterable.from(events).filter(notNull()).toList();
686 }
687
688 // Creates a new port based on the port description adds it to the map and
689 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700690 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700691 private DeviceEvent createPort(Device device, Port newPort,
692 Map<PortNumber, Port> ports) {
693 ports.put(newPort.number(), newPort);
694 return new DeviceEvent(PORT_ADDED, device, newPort);
695 }
696
697 // Checks if the specified port requires update and if so, it replaces the
698 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700699 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700700 private DeviceEvent updatePort(Device device, Port oldPort,
701 Port newPort,
702 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100703
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700704 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700705 oldPort.type() != newPort.type() ||
706 oldPort.portSpeed() != newPort.portSpeed() ||
707 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700708 ports.put(oldPort.number(), newPort);
709 return new DeviceEvent(PORT_UPDATED, device, newPort);
710 }
711 return null;
712 }
713
Michal Machce774332017-01-25 11:02:55 +0100714 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
715
716 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
717 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
718
719 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
720 }
721
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700722 // Prunes the specified list of ports based on which ports are in the
723 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700724 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700725 private List<DeviceEvent> pruneOldPorts(Device device,
726 Map<PortNumber, Port> ports,
727 Set<PortNumber> processed) {
728 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700729 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700730 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700731 Entry<PortNumber, Port> e = iterator.next();
732 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700733 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700734 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700735 iterator.remove();
736 }
737 }
738 return events;
739 }
740
741 // Gets the map of ports for the specified device; if one does not already
742 // exist, it creates and registers a new one.
743 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700744 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700745 }
746
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700747 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700748 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700749 Map<ProviderId, DeviceDescriptions> r;
750 r = deviceDescs.get(deviceId);
751 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700752 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700753 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
754 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
755 if (concurrentlyAdded != null) {
756 r = concurrentlyAdded;
757 }
758 }
759 return r;
760 }
761
762 // Guarded by deviceDescs value (=Device lock)
763 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
764 Map<ProviderId, DeviceDescriptions> device,
765 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700766 synchronized (device) {
767 DeviceDescriptions r = device.get(providerId);
768 if (r == null) {
769 r = new DeviceDescriptions(deltaDesc);
770 device.put(providerId, r);
771 }
772 return r;
773 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700774 }
775
776 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700777 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
778 DeviceId deviceId,
779 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700780 final Timestamp newTimestamp;
781 try {
782 newTimestamp = deviceClockService.getTimestamp(deviceId);
783 } catch (IllegalStateException e) {
784 log.info("Timestamp was not available for device {}", deviceId);
785 log.debug(" discarding {}", portDescription);
786 // Failed to generate timestamp. Ignoring.
787 // See updatePorts comment
788 return null;
789 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700790 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700791 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700792 final DeviceEvent event;
793 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800794 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
795 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700796 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800797 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700798 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700799 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700800 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700801 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700802 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800803 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700804 }
805 return event;
806 }
807
808 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700809 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700810 Device device = devices.get(deviceId);
811 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
812
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700813 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700814 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
815
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700816 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700817
818 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
819 log.debug("Ignoring outdated event: {}", deltaDesc);
820 return null;
821 }
822
823 DeviceDescriptions descs = descsMap.get(providerId);
824 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700825 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700826 "Device description for Device ID %s from Provider %s was not found",
827 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700828
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700829 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
830 final PortNumber number = deltaDesc.value().portNumber();
831 final Port oldPort = ports.get(number);
832 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700833 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100834 boolean toDelete = false;
835
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700836 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700837 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700838 // on new port or valid update
839 // update description
840 descs.putPortDesc(deltaDesc);
841 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100842 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700843 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700844 // same or outdated event, ignored.
845 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700846 return null;
847 }
848
849 if (oldPort == null) {
850 return createPort(device, newPort, ports);
851 } else {
Michal Machce774332017-01-25 11:02:55 +0100852 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700853 }
854 }
855 }
856
857 @Override
858 public List<Port> getPorts(DeviceId deviceId) {
859 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
860 if (ports == null) {
861 return Collections.emptyList();
862 }
863 return ImmutableList.copyOf(ports.values());
864 }
865
866 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700867 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
868 DeviceId deviceId) {
869 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
870 if (descs == null) {
Donghyeok Ho6de4fb92018-01-31 11:04:19 +0900871 return Stream.empty();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700872 }
873 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
874 final Optional<DeviceDescriptions> devDescs;
875 synchronized (descs) {
876 devDescs = Optional.ofNullable(descs.get(pid));
877 }
878 // DeviceDescriptions is concurrent access-safe
879 return devDescs
880 .map(dd -> dd.getPortDescs().values().stream()
881 .map(Timestamped::value))
882 .orElse(Stream.empty());
883 }
884
885 @Override
sangho538108b2015-04-08 14:29:20 -0700886 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200887 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700888
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200889 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
890 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
891 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
892
893 if (prvStatsMap != null) {
894 for (PortStatistics newStats : newStatsCollection) {
895 PortNumber port = PortNumber.portNumber(newStats.port());
896 PortStatistics prvStats = prvStatsMap.get(port);
897 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
898 PortStatistics deltaStats = builder.build();
899 if (prvStats != null) {
900 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
901 }
902 deltaStatsMap.put(port, deltaStats);
903 newStatsMap.put(port, newStats);
904 }
905 } else {
906 for (PortStatistics newStats : newStatsCollection) {
907 PortNumber port = PortNumber.portNumber(newStats.port());
908 newStatsMap.put(port, newStats);
909 }
sangho538108b2015-04-08 14:29:20 -0700910 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200911 devicePortDeltaStats.put(deviceId, deltaStatsMap);
912 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200913 // DeviceEvent returns null because of InternalPortStatsListener usage
914 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200915 }
916
917 /**
918 * Calculate delta statistics by subtracting previous from new statistics.
919 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700920 * @param deviceId device identifier
921 * @param prvStats previous port statistics
922 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200923 * @return PortStatistics
924 */
925 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
926 // calculate time difference
927 long deltaStatsSec, deltaStatsNano;
928 if (newStats.durationNano() < prvStats.durationNano()) {
929 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
930 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
931 } else {
932 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
933 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
934 }
935 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
936 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
937 .setPort(newStats.port())
938 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
939 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
940 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
941 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
942 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
943 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
944 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
945 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
946 .setDurationSec(deltaStatsSec)
947 .setDurationNano(deltaStatsNano)
948 .build();
949 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700950 }
951
952 @Override
953 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700954 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
955 if (portStats == null) {
956 return Collections.emptyList();
957 }
958 return ImmutableList.copyOf(portStats.values());
959 }
960
961 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530962 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
963 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
964 if (portStatsMap == null) {
965 return null;
966 }
967 PortStatistics portStats = portStatsMap.get(portNumber);
968 return portStats;
969 }
970
971 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200972 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
973 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
974 if (portStats == null) {
975 return Collections.emptyList();
976 }
977 return ImmutableList.copyOf(portStats.values());
978 }
979
980 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530981 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
982 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
983 if (portStatsMap == null) {
984 return null;
985 }
986 PortStatistics portStats = portStatsMap.get(portNumber);
987 return portStats;
988 }
989
990 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700991 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
992 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
993 return ports == null ? null : ports.get(portNumber);
994 }
995
996 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700997 public PortDescription getPortDescription(ProviderId pid,
998 DeviceId deviceId,
999 PortNumber portNumber) {
1000 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1001 if (descs == null) {
1002 return null;
1003 }
1004 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1005 final Optional<DeviceDescriptions> devDescs;
1006 synchronized (descs) {
1007 devDescs = Optional.ofNullable(descs.get(pid));
1008 }
1009 // DeviceDescriptions is concurrent access-safe
1010 return devDescs
1011 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1012 .map(Timestamped::value)
1013 .orElse(null);
1014 }
1015
1016 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001017 public boolean isAvailable(DeviceId deviceId) {
1018 return availableDevices.contains(deviceId);
1019 }
1020
1021 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001022 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001023 final NodeId myId = clusterService.getLocalNode().id();
1024 NodeId master = mastershipService.getMasterFor(deviceId);
1025
1026 // if there exist a master, forward
1027 // if there is no master, try to become one and process
1028
1029 boolean relinquishAtEnd = false;
1030 if (master == null) {
1031 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1032 if (myRole != MastershipRole.NONE) {
1033 relinquishAtEnd = true;
1034 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001035 log.debug("Temporarily requesting role for {} to remove", deviceId);
Jordan Haltermanf1c602d2017-10-18 11:26:52 -07001036 if (mastershipService.requestRoleFor(deviceId).join() == MastershipRole.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);
jaegonkim73c21bd2018-01-13 10:52:02 +09001455 if (localLatest == null || (rOffline != null && 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 {
Jayasree Ghosh7d96d6a2017-02-27 18:35:32 +05301586 DeviceEvent event = removeDevice(did);
1587 notifyDelegateIfNotNull(event);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001588 } catch (Exception e) {
1589 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001590 }
1591 }
1592
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001593 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1594 DeviceId deviceId = event.deviceId();
1595 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001596
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001597 try {
1598 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1599 } catch (Exception e) {
1600 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001601 }
1602 }
1603
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001604 private void handlePortEvent(InternalPortEvent event) {
1605 ProviderId providerId = event.providerId();
1606 DeviceId deviceId = event.deviceId();
1607 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001608
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001609 if (getDevice(deviceId) == null) {
1610 log.debug("{} not found on this node yet, ignoring.", deviceId);
1611 // Note: dropped information will be recovered by anti-entropy
1612 return;
1613 }
Madan Jampani47c93732014-10-06 20:46:08 -07001614
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001615 try {
1616 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1617 } catch (Exception e) {
1618 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001619 }
1620 }
1621
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001622 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1623 ProviderId providerId = event.providerId();
1624 DeviceId deviceId = event.deviceId();
1625 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001626
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001627 if (getDevice(deviceId) == null) {
1628 log.debug("{} not found on this node yet, ignoring.", deviceId);
1629 // Note: dropped information will be recovered by anti-entropy
1630 return;
1631 }
Madan Jampani47c93732014-10-06 20:46:08 -07001632
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001633 try {
1634 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1635 } catch (Exception e) {
1636 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001637 }
1638 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001639
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001640 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1641 try {
1642 handleAdvertisement(advertisement);
1643 } catch (Exception e) {
1644 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001645 }
1646 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001647
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001648 private class InternalPortStatsListener
1649 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1650 @Override
1651 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1652 if (event.type() == PUT) {
1653 Device device = devices.get(event.key());
1654 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001655 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001656 }
1657 }
1658 }
1659 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001660}