blob: c77035927efe70e0e4b4f83314d08fb32ab723b0 [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
Thomas Vachuskaa651de12018-04-19 12:11:09 -070018import com.google.common.collect.FluentIterable;
19import com.google.common.collect.ImmutableList;
20import com.google.common.collect.Maps;
21import com.google.common.collect.Sets;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070022import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070023import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
26import org.apache.felix.scr.annotations.Reference;
27import org.apache.felix.scr.annotations.ReferenceCardinality;
28import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080029import org.onlab.packet.ChassisId;
30import org.onlab.util.KryoNamespace;
Brian O'Connorabafb502014-12-02 22:26:20 -080031import org.onosproject.cluster.ClusterService;
32import org.onosproject.cluster.ControllerNode;
33import org.onosproject.cluster.NodeId;
34import org.onosproject.mastership.MastershipService;
Brian O'Connorabafb502014-12-02 22:26:20 -080035import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070036import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080037import org.onosproject.net.AnnotationsUtil;
38import org.onosproject.net.DefaultAnnotations;
39import org.onosproject.net.DefaultDevice;
40import org.onosproject.net.DefaultPort;
41import org.onosproject.net.Device;
42import org.onosproject.net.Device.Type;
43import org.onosproject.net.DeviceId;
44import org.onosproject.net.MastershipRole;
45import org.onosproject.net.Port;
46import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070047import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080048import org.onosproject.net.device.DeviceClockService;
49import org.onosproject.net.device.DeviceDescription;
50import org.onosproject.net.device.DeviceEvent;
51import org.onosproject.net.device.DeviceStore;
52import org.onosproject.net.device.DeviceStoreDelegate;
53import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070054import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.net.provider.ProviderId;
56import org.onosproject.store.AbstractStore;
57import org.onosproject.store.Timestamp;
58import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
Brian O'Connorabafb502014-12-02 22:26:20 -080059import org.onosproject.store.cluster.messaging.MessageSubject;
Jordan Haltermanebedbb52017-08-08 15:57:50 -070060import org.onosproject.store.impl.MastershipBasedTimestamp;
Brian O'Connorabafb502014-12-02 22:26:20 -080061import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070062import org.onosproject.store.serializers.KryoNamespaces;
Brian O'Connor6de2e202015-05-21 14:30:41 -070063import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070064import org.onosproject.store.service.EventuallyConsistentMap;
65import org.onosproject.store.service.EventuallyConsistentMapEvent;
66import org.onosproject.store.service.EventuallyConsistentMapListener;
67import org.onosproject.store.service.MultiValuedTimestamp;
Jordan Halterman2c83a102017-08-20 17:11:41 -070068import org.onosproject.store.service.Serializer;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070069import org.onosproject.store.service.StorageService;
70import org.onosproject.store.service.WallClockTimestamp;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070071import org.slf4j.Logger;
72
Thomas Vachuskaa651de12018-04-19 12:11:09 -070073import java.io.IOException;
74import java.util.ArrayList;
75import java.util.Collection;
76import java.util.Collections;
77import java.util.HashMap;
78import java.util.HashSet;
79import java.util.Iterator;
80import java.util.List;
81import java.util.Map;
82import java.util.Map.Entry;
83import java.util.Objects;
84import java.util.Optional;
85import java.util.Set;
86import java.util.concurrent.ConcurrentHashMap;
87import java.util.concurrent.ConcurrentMap;
88import java.util.concurrent.ExecutorService;
89import java.util.concurrent.ScheduledExecutorService;
90import java.util.concurrent.TimeUnit;
91import java.util.function.Consumer;
92import java.util.stream.Stream;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070093
94import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070095import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070096import static com.google.common.base.Verify.verify;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -080097import static java.util.concurrent.Executors.newCachedThreadPool;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080098import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080099import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800100import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800101import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
Thomas Vachuskaa651de12018-04-19 12:11:09 -0700102import static org.onosproject.net.device.DeviceEvent.Type.*;
103import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700104import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVED;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700105import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800106import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700107
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700108/**
109 * Manages inventory of infrastructure devices using gossip protocol to distribute
110 * information.
111 */
112@Component(immediate = true)
113@Service
114public class GossipDeviceStore
115 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
116 implements DeviceStore {
117
118 private final Logger log = getLogger(getClass());
119
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700120 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800121 // Timeout in milliseconds to process device or ports on remote master node
122 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700123
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700124 // innerMap is used to lock a Device, thus instance should never be replaced.
125 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700126 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700127 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700128
129 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700130 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
131 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700132
133 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200134 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700135 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
136 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700137
138 // to be updated under Device lock
139 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
140 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700141
142 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700143 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700144
145 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700146 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700147
Madan Jampani47c93732014-10-06 20:46:08 -0700148 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700149 protected StorageService storageService;
150
151 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700152 protected ClusterCommunicationService clusterCommunicator;
153
Madan Jampani53e44e62014-10-07 12:39:51 -0700154 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
155 protected ClusterService clusterService;
156
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700157 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
158 protected MastershipService mastershipService;
159
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800160 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
161 protected MastershipTermService termService;
162
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700163 private static final Timestamp DEFAULT_TIMESTAMP = new MastershipBasedTimestamp(0, 0);
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800164
Jordan Halterman2c83a102017-08-20 17:11:41 -0700165 protected static final Serializer SERIALIZER = Serializer.using(KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800166 .register(DistributedStoreSerializers.STORE_COMMON)
167 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
168 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
Palash Kala6c526062018-04-03 18:25:11 +0900169 .register(new InternalDeviceStatusChangeEventSerializer(), InternalDeviceStatusChangeEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700170 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800171 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
172 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700173 .register(DeviceAntiEntropyAdvertisement.class)
174 .register(DeviceFragmentId.class)
175 .register(PortFragmentId.class)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700176 .build("GossipDevice"));
Madan Jampani53e44e62014-10-07 12:39:51 -0700177
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800178 private ExecutorService executor;
179
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800180 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700181
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800182 // TODO make these anti-entropy parameters configurable
183 private long initialDelaySec = 5;
184 private long periodSec = 5;
185
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700186 @Activate
187 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800188 executor = newCachedThreadPool(groupedThreads("onos/device", "fg-%d", log));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800189
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800190 backgroundExecutor =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800191 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d", log)));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700192
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700193 addSubscriber(DEVICE_UPDATE, this::handleDeviceEvent);
Palash Kala6c526062018-04-03 18:25:11 +0900194 addSubscriber(DEVICE_STATUS_CHANGE, this::handleDeviceStatusChangeEvent);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700195 addSubscriber(DEVICE_REMOVE_REQ, this::handleRemoveRequest);
196 addSubscriber(DEVICE_REMOVED, this::handleDeviceRemovedEvent);
197 addSubscriber(PORT_UPDATE, this::handlePortEvent);
198 addSubscriber(PORT_STATUS_UPDATE, this::handlePortStatusEvent);
199 addSubscriber(DEVICE_ADVERTISE, this::handleDeviceAdvertisement);
Madan Jampani2af244a2015-02-22 13:12:01 -0800200
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700201 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800202 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700203 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700204
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700205 // Create a distributed map for port stats.
206 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
207 .register(KryoNamespaces.API)
HIGUCHI Yuta03666a32016-05-18 11:49:09 -0700208 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
209 .register(MultiValuedTimestamp.class);
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700210
211 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
212 .withName("port-stats")
213 .withSerializer(deviceDataSerializer)
214 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700215 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700216 .withTombstonesDisabled()
217 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200218 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
219 eventuallyConsistentMapBuilder()
220 .withName("port-stats-delta")
221 .withSerializer(deviceDataSerializer)
222 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
223 .withTimestampProvider((k, v) -> new WallClockTimestamp())
224 .withTombstonesDisabled()
225 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700226 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700227 log.info("Started");
228 }
229
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700230 private <M> void addSubscriber(MessageSubject subject, Consumer<M> handler) {
231 clusterCommunicator.addSubscriber(subject, SERIALIZER::decode, handler, executor);
232 }
233
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700234 @Deactivate
235 public void deactivate() {
Frank Wange0eb5ce2016-07-01 18:21:25 +0800236 devicePortStats.removeListener(portStatsListener);
Madan Jampani632f16b2015-08-11 12:42:59 -0700237 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200238 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800239 executor.shutdownNow();
240
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800241 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700242 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800243 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700244 log.error("Timeout during executor shutdown");
245 }
246 } catch (InterruptedException e) {
247 log.error("Error during executor shutdown", e);
Ray Milkey5c7d4882018-02-05 14:50:39 -0800248 Thread.currentThread().interrupt();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700249 }
250
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700251 deviceDescs.clear();
252 devices.clear();
253 devicePorts.clear();
254 availableDevices.clear();
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700255 clusterCommunicator.removeSubscriber(DEVICE_UPDATE);
Palash Kala6c526062018-04-03 18:25:11 +0900256 clusterCommunicator.removeSubscriber(DEVICE_STATUS_CHANGE);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700257 clusterCommunicator.removeSubscriber(DEVICE_REMOVE_REQ);
258 clusterCommunicator.removeSubscriber(DEVICE_REMOVED);
259 clusterCommunicator.removeSubscriber(PORT_UPDATE);
260 clusterCommunicator.removeSubscriber(PORT_STATUS_UPDATE);
261 clusterCommunicator.removeSubscriber(DEVICE_ADVERTISE);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700262 log.info("Stopped");
263 }
264
265 @Override
266 public int getDeviceCount() {
267 return devices.size();
268 }
269
270 @Override
mskala0d0c6832017-07-12 11:21:23 +0200271 public int getAvailableDeviceCount() {
272 return availableDevices.size();
273 }
274
275 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700276 public Iterable<Device> getDevices() {
277 return Collections.unmodifiableCollection(devices.values());
278 }
279
280 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800281 public Iterable<Device> getAvailableDevices() {
282 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700283 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800284 }
285
286 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700287 public Device getDevice(DeviceId deviceId) {
288 return devices.get(deviceId);
289 }
290
291 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700292 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700293 DeviceId deviceId,
294 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800295 NodeId localNode = clusterService.getLocalNode().id();
296 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Jordan Haltermanf9f55632017-12-19 14:56:08 -0800297 boolean isMaster = localNode.equals(deviceNode);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800298
299 // Process device update only if we're the master,
300 // otherwise signal the actual master.
301 DeviceEvent deviceEvent = null;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800302
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700303 // If this node is the master for the device, acquire a new timestamp. Otherwise,
304 // use a 0,0 or tombstone timestamp to create the device if it doesn't already exist.
Jordan Haltermanf9f55632017-12-19 14:56:08 -0800305 Timestamp newTimestamp;
306 try {
307 newTimestamp = isMaster
308 ? deviceClockService.getTimestamp(deviceId)
309 : removalRequest.getOrDefault(deviceId, DEFAULT_TIMESTAMP);
310 } catch (IllegalStateException e) {
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -0800311 newTimestamp = removalRequest.getOrDefault(deviceId, DEFAULT_TIMESTAMP);
Jordan Haltermanf9f55632017-12-19 14:56:08 -0800312 isMaster = false;
313 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700314 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
315 final Timestamped<DeviceDescription> mergedDesc;
316 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800317
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700318 synchronized (device) {
319 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
Jordan Halterman8a0b3972017-08-15 16:14:18 -0700320 if (deviceEvent == null) {
321 return null;
322 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700323 mergedDesc = device.get(providerId).getDeviceDesc();
324 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800325
Thomas Vachuskaa651de12018-04-19 12:11:09 -0700326 // FIXME: This may result in duplicate events as each instance reports on the new device
327 // regardless of whether it is a master or not.
328 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
329 providerId, deviceId);
330 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800331
332 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700333 }
334
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700335 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700336 DeviceId deviceId,
337 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700338
339 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800340 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700341 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700342
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800343 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700344 // locking per device
345
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700346 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
347 log.debug("Ignoring outdated event: {}", deltaDesc);
348 return null;
349 }
350
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800351 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700352
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700353 final Device oldDevice = devices.get(deviceId);
354 final Device newDevice;
355
356 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700357 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700358 // on new device or valid update
359 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800360 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700361 } else {
362 // outdated event, ignored.
363 return null;
364 }
365 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700366 // REGISTER
367 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700368 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700369 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700370 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700371 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700372 } else {
373 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700374 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
375 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700376 }
377 }
378 }
379
380 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700381 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700382 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700383 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700384
385 // update composed device cache
386 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
387 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700388 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
389 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700390
391 if (!providerId.isAncillary()) {
Palash Kala6c526062018-04-03 18:25:11 +0900392 markOnline(newDevice.id(), timestamp, false);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700393 }
394
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700395 log.debug("Device {} added", newDevice.id());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700396 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
397 }
398
399 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700400 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700401 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700402 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700403 Device newDevice, Timestamp newTimestamp,
404 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700405 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700406 boolean propertiesChanged =
407 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700408 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
mskala4b2081a2017-06-12 16:39:50 +0200409 !Objects.equals(oldDevice.providerId(), newDevice.providerId()) ||
410 !Objects.equals(oldDevice.chassisId(), newDevice.chassisId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700411 boolean annotationsChanged =
412 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700413
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700414 // Primary providers can respond to all changes, but ancillary ones
415 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800416 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700417 if ((providerId.isAncillary() && annotationsChanged) ||
418 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700419 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
420 if (!replaced) {
421 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700422 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800423 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700424 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700425
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700426 log.debug("Device {} updated", newDevice.id());
alshabibdc5d8bd2015-11-02 15:41:29 -0800427 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700428 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800429
helenyrwufd296b62016-06-22 17:43:02 -0700430 if (!providerId.isAncillary() && forceAvailable) {
Palash Kala6c526062018-04-03 18:25:11 +0900431 notifyDelegateIfNotNull(markOnline(newDevice.id(), newTimestamp, false));
alshabibdc5d8bd2015-11-02 15:41:29 -0800432 }
433 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700434 }
435
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700436 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700437 // update composed device cache
438 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
439 verify(oldDevice == null,
440 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
441 providerId, oldDevice, newDevice);
442
443 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700444 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700445 }
446
447 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
448 }
449
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700450 @Override
451 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700452 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
453 }
454
455 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700456 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700457 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700458 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700459 deviceId, timestamp);
Palash Kala6c526062018-04-03 18:25:11 +0900460 notifyPeers(new InternalDeviceStatusChangeEvent(deviceId, timestamp, false));
Madan Jampani25322532014-10-08 11:20:38 -0700461 }
462 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700463 }
464
465 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700466 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700467 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700468
469 // locking device
470 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700471 // accept off-line if given timestamp is newer than
472 // the latest Timestamp from Primary provider
473 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
jaegonkim73c21bd2018-01-13 10:52:02 +0900474 if (primDescs != null) {
475 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
476 if (lastTimestamp == null) {
477 lastTimestamp = deviceClockService.getTimestamp(deviceId);
478 }
479 if (timestamp.compareTo(lastTimestamp) <= 0) {
480 // outdated event ignore
481 return null;
482 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700483 }
484
485 offline.put(deviceId, timestamp);
486
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700487 Device device = devices.get(deviceId);
488 if (device == null) {
489 return null;
490 }
491 boolean removed = availableDevices.remove(deviceId);
492 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700493 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700494 }
495 return null;
496 }
497 }
498
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700499 @Override
Palash Kala6c526062018-04-03 18:25:11 +0900500 public DeviceEvent markOnline(DeviceId deviceId) {
501 return markOnline(deviceId, deviceClockService.getTimestamp(deviceId), true);
helenyrwufd296b62016-06-22 17:43:02 -0700502 }
503
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700504 /**
505 * Marks the device as available if the given timestamp is not outdated,
506 * compared to the time the device has been marked offline.
507 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700508 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700509 * @param timestamp of the event triggering this change.
Palash Kala6c526062018-04-03 18:25:11 +0900510 * @param notifyPeers if the event needs to be notified to peers.
511 * @return ready to send event describing what occurred; null if no change
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700512 */
Palash Kala6c526062018-04-03 18:25:11 +0900513 private DeviceEvent markOnline(DeviceId deviceId, Timestamp timestamp, boolean notifyPeers) {
514 final DeviceEvent event = markOnlineInternal(deviceId, timestamp);
515 if (event != null && notifyPeers) {
516 log.debug("Notifying peers of a device online topology event for deviceId: {} {}",
517 deviceId, timestamp);
518 notifyPeers(new InternalDeviceStatusChangeEvent(deviceId, timestamp, true));
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700519 }
Palash Kala6c526062018-04-03 18:25:11 +0900520 return event;
521 }
522
523 // Guarded by deviceDescs value (=Device lock)
524 private DeviceEvent markOnlineInternal(DeviceId deviceId, Timestamp timestamp) {
525 if (devices.containsKey(deviceId)) {
526 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
527 synchronized (deviceLock) {
528 // accept on-line if given timestamp is newer than
529 // the latest offline request Timestamp
530 Timestamp offlineTimestamp = offline.get(deviceId);
531 if (offlineTimestamp == null ||
532 offlineTimestamp.compareTo(timestamp) < 0) {
533 offline.remove(deviceId);
534 Device device = devices.get(deviceId);
535 boolean add = availableDevices.add(deviceId);
536 if (add) {
537 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
538 }
539 }
540 }
541 }
542 log.warn("Device {} does not exist in store", deviceId);
543 return null;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700544 }
545
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700546 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700547 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700548 DeviceId deviceId,
549 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700550
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800551 NodeId localNode = clusterService.getLocalNode().id();
552 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
553 // since it will trigger distributed store read.
554 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
555 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
556 // If we don't care much about topology performance, then it might be OK.
557 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700558
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800559 // Process port update only if we're the master of the device,
560 // otherwise signal the actual master.
561 List<DeviceEvent> deviceEvents = null;
562 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700563
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800564 final Timestamp newTimestamp;
565 try {
566 newTimestamp = deviceClockService.getTimestamp(deviceId);
567 } catch (IllegalStateException e) {
568 log.info("Timestamp was not available for device {}", deviceId);
569 log.debug(" discarding {}", portDescriptions);
570 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700571
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800572 // Possible situation:
573 // Device connected and became master for short period of time,
574 // but lost mastership before this instance had the chance to
575 // retrieve term information.
576
577 // Information dropped here is expected to be recoverable by
578 // device probing after mastership change
579
580 return Collections.emptyList();
581 }
582 log.debug("timestamp for {} {}", deviceId, newTimestamp);
583
584 final Timestamped<List<PortDescription>> timestampedInput
585 = new Timestamped<>(portDescriptions, newTimestamp);
586 final Timestamped<List<PortDescription>> merged;
587
588 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
589
590 synchronized (device) {
591 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
592 final DeviceDescriptions descs = device.get(providerId);
593 List<PortDescription> mergedList =
594 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700595 .transform(input ->
596 // lookup merged port description
597 descs.getPortDesc(input.portNumber()).value()
598 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700599 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800600 }
601
602 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700603 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700604 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800605 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
606 }
607
608 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700609 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700610 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700611
Ray Milkeyfe0e0852018-01-18 11:14:05 -0800612 return deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700613 }
614
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700615 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700616 DeviceId deviceId,
617 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700618
619 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700620 if (device == null) {
621 log.debug("Device is no longer valid: {}", deviceId);
622 return Collections.emptyList();
623 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700624
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700625 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700626 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
627
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700628 List<DeviceEvent> events = new ArrayList<>();
629 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700630
631 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
632 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700633 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700634 }
635
636 DeviceDescriptions descs = descsMap.get(providerId);
637 // every provider must provide DeviceDescription.
638 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700639 "Device description for Device ID %s from Provider %s was not found",
640 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700641
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700642 Map<PortNumber, Port> ports = getPortMap(deviceId);
643
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700644 final Timestamp newTimestamp = portDescriptions.timestamp();
645
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700646 // Add new ports
647 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700648 for (PortDescription portDescription : portDescriptions.value()) {
649 final PortNumber number = portDescription.portNumber();
650 processed.add(number);
651
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700652 final Port oldPort = ports.get(number);
653 final Port newPort;
Palash Kala8d30b612018-03-02 11:06:10 +0900654 boolean isRemoved = portDescription.isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700655
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700656
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700657 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
658 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700659 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700660 // on new port or valid update
661 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700662 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700663 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700664 newPort = composePort(device, number, descsMap);
665 } else {
666 // outdated event, ignored.
667 continue;
668 }
669
Palash Kala8d30b612018-03-02 11:06:10 +0900670 if (isRemoved && oldPort != null) {
671 events.add(removePort(deviceId, oldPort.number()));
672 } else if (!isRemoved) {
673 events.add(oldPort == null ?
674 createPort(device, newPort, ports) :
675 updatePort(device, oldPort, newPort, ports));
676 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700677 }
678
679 events.addAll(pruneOldPorts(device, ports, processed));
680 }
681 return FluentIterable.from(events).filter(notNull()).toList();
682 }
683
684 // Creates a new port based on the port description adds it to the map and
685 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700686 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700687 private DeviceEvent createPort(Device device, Port newPort,
688 Map<PortNumber, Port> ports) {
689 ports.put(newPort.number(), newPort);
690 return new DeviceEvent(PORT_ADDED, device, newPort);
691 }
692
693 // Checks if the specified port requires update and if so, it replaces the
694 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700695 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700696 private DeviceEvent updatePort(Device device, Port oldPort,
697 Port newPort,
698 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100699
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700700 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700701 oldPort.type() != newPort.type() ||
702 oldPort.portSpeed() != newPort.portSpeed() ||
703 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700704 ports.put(oldPort.number(), newPort);
705 return new DeviceEvent(PORT_UPDATED, device, newPort);
706 }
707 return null;
708 }
709
Michal Machce774332017-01-25 11:02:55 +0100710 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
711
712 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
713 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
714
715 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
716 }
717
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700718 // Prunes the specified list of ports based on which ports are in the
719 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700720 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700721 private List<DeviceEvent> pruneOldPorts(Device device,
722 Map<PortNumber, Port> ports,
723 Set<PortNumber> processed) {
724 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700725 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700726 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700727 Entry<PortNumber, Port> e = iterator.next();
728 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700729 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700730 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700731 iterator.remove();
732 }
733 }
734 return events;
735 }
736
737 // Gets the map of ports for the specified device; if one does not already
738 // exist, it creates and registers a new one.
739 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700740 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700741 }
742
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700743 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700744 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700745 Map<ProviderId, DeviceDescriptions> r;
746 r = deviceDescs.get(deviceId);
747 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700748 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700749 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
750 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
751 if (concurrentlyAdded != null) {
752 r = concurrentlyAdded;
753 }
754 }
755 return r;
756 }
757
758 // Guarded by deviceDescs value (=Device lock)
759 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
760 Map<ProviderId, DeviceDescriptions> device,
761 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700762 synchronized (device) {
763 DeviceDescriptions r = device.get(providerId);
764 if (r == null) {
765 r = new DeviceDescriptions(deltaDesc);
766 device.put(providerId, r);
767 }
768 return r;
769 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700770 }
771
772 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700773 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
774 DeviceId deviceId,
775 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700776 final Timestamp newTimestamp;
777 try {
778 newTimestamp = deviceClockService.getTimestamp(deviceId);
779 } catch (IllegalStateException e) {
780 log.info("Timestamp was not available for device {}", deviceId);
781 log.debug(" discarding {}", portDescription);
782 // Failed to generate timestamp. Ignoring.
783 // See updatePorts comment
784 return null;
785 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700786 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700787 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700788 final DeviceEvent event;
789 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800790 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
791 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700792 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800793 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700794 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700795 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700796 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700797 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700798 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800799 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700800 }
801 return event;
802 }
803
804 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700805 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700806 Device device = devices.get(deviceId);
807 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
808
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700809 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700810 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
811
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700812 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700813
814 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
815 log.debug("Ignoring outdated event: {}", deltaDesc);
816 return null;
817 }
818
819 DeviceDescriptions descs = descsMap.get(providerId);
820 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700821 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700822 "Device description for Device ID %s from Provider %s was not found",
823 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700824
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700825 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
826 final PortNumber number = deltaDesc.value().portNumber();
827 final Port oldPort = ports.get(number);
828 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700829 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100830 boolean toDelete = false;
831
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700832 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700833 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700834 // on new port or valid update
835 // update description
836 descs.putPortDesc(deltaDesc);
837 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100838 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700839 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700840 // same or outdated event, ignored.
841 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700842 return null;
843 }
844
845 if (oldPort == null) {
846 return createPort(device, newPort, ports);
847 } else {
Michal Machce774332017-01-25 11:02:55 +0100848 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700849 }
850 }
851 }
852
853 @Override
854 public List<Port> getPorts(DeviceId deviceId) {
855 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
856 if (ports == null) {
857 return Collections.emptyList();
858 }
859 return ImmutableList.copyOf(ports.values());
860 }
861
862 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700863 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
864 DeviceId deviceId) {
865 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
866 if (descs == null) {
Donghyeok Ho6de4fb92018-01-31 11:04:19 +0900867 return Stream.empty();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700868 }
869 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
870 final Optional<DeviceDescriptions> devDescs;
871 synchronized (descs) {
872 devDescs = Optional.ofNullable(descs.get(pid));
873 }
874 // DeviceDescriptions is concurrent access-safe
875 return devDescs
876 .map(dd -> dd.getPortDescs().values().stream()
877 .map(Timestamped::value))
878 .orElse(Stream.empty());
879 }
880
881 @Override
sangho538108b2015-04-08 14:29:20 -0700882 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200883 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700884
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200885 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
886 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
887 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
888
889 if (prvStatsMap != null) {
890 for (PortStatistics newStats : newStatsCollection) {
891 PortNumber port = PortNumber.portNumber(newStats.port());
892 PortStatistics prvStats = prvStatsMap.get(port);
893 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
894 PortStatistics deltaStats = builder.build();
895 if (prvStats != null) {
896 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
897 }
898 deltaStatsMap.put(port, deltaStats);
899 newStatsMap.put(port, newStats);
900 }
901 } else {
902 for (PortStatistics newStats : newStatsCollection) {
903 PortNumber port = PortNumber.portNumber(newStats.port());
904 newStatsMap.put(port, newStats);
905 }
sangho538108b2015-04-08 14:29:20 -0700906 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200907 devicePortDeltaStats.put(deviceId, deltaStatsMap);
908 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200909 // DeviceEvent returns null because of InternalPortStatsListener usage
910 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200911 }
912
913 /**
914 * Calculate delta statistics by subtracting previous from new statistics.
915 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700916 * @param deviceId device identifier
917 * @param prvStats previous port statistics
918 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200919 * @return PortStatistics
920 */
921 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
922 // calculate time difference
923 long deltaStatsSec, deltaStatsNano;
924 if (newStats.durationNano() < prvStats.durationNano()) {
925 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
926 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
927 } else {
928 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
929 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
930 }
931 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
932 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
933 .setPort(newStats.port())
934 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
935 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
936 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
937 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
938 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
939 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
940 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
941 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
942 .setDurationSec(deltaStatsSec)
943 .setDurationNano(deltaStatsNano)
944 .build();
945 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700946 }
947
948 @Override
949 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700950 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
951 if (portStats == null) {
952 return Collections.emptyList();
953 }
954 return ImmutableList.copyOf(portStats.values());
955 }
956
957 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530958 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
959 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
960 if (portStatsMap == null) {
961 return null;
962 }
963 PortStatistics portStats = portStatsMap.get(portNumber);
964 return portStats;
965 }
966
967 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200968 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
969 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
970 if (portStats == null) {
971 return Collections.emptyList();
972 }
973 return ImmutableList.copyOf(portStats.values());
974 }
975
976 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530977 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
978 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
979 if (portStatsMap == null) {
980 return null;
981 }
982 PortStatistics portStats = portStatsMap.get(portNumber);
983 return portStats;
984 }
985
986 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700987 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
988 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
989 return ports == null ? null : ports.get(portNumber);
990 }
991
992 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700993 public PortDescription getPortDescription(ProviderId pid,
994 DeviceId deviceId,
995 PortNumber portNumber) {
996 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
997 if (descs == null) {
998 return null;
999 }
1000 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1001 final Optional<DeviceDescriptions> devDescs;
1002 synchronized (descs) {
1003 devDescs = Optional.ofNullable(descs.get(pid));
1004 }
1005 // DeviceDescriptions is concurrent access-safe
1006 return devDescs
1007 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1008 .map(Timestamped::value)
1009 .orElse(null);
1010 }
1011
1012 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001013 public boolean isAvailable(DeviceId deviceId) {
1014 return availableDevices.contains(deviceId);
1015 }
1016
1017 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001018 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001019 final NodeId myId = clusterService.getLocalNode().id();
1020 NodeId master = mastershipService.getMasterFor(deviceId);
1021
1022 // if there exist a master, forward
1023 // if there is no master, try to become one and process
1024
1025 boolean relinquishAtEnd = false;
1026 if (master == null) {
1027 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1028 if (myRole != MastershipRole.NONE) {
1029 relinquishAtEnd = true;
1030 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001031 log.debug("Temporarily requesting role for {} to remove", deviceId);
Jordan Haltermanf1c602d2017-10-18 11:26:52 -07001032 if (mastershipService.requestRoleFor(deviceId).join() == MastershipRole.MASTER) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001033 master = myId;
1034 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001035 }
1036
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001037 boolean isMaster = myId.equals(master);
1038
1039 // If this node is not the master, forward the request.
1040 if (!isMaster) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001041 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001042 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001043
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001044 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001045 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001046 /* error log:
1047 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1048 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001049 }
1050
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001051 // If this node is the master, get a timestamp. Otherwise, default to the current device timestamp.
1052 Timestamp timestamp = isMaster ? deviceClockService.getTimestamp(deviceId) : null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001053
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001054 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001055
1056 // If this node is the master, update peers.
1057 if (isMaster && event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001058 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001059 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001060 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001061 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001062
1063 // Relinquish mastership if acquired to remove the device.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001064 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001065 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001066 mastershipService.relinquishMastership(deviceId);
1067 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001068 return event;
1069 }
1070
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001071 private DeviceEvent removeDeviceInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001072
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001073 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001074 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001075 // accept removal request if given timestamp is newer than
1076 // the latest Timestamp from Primary provider
1077 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001078 if (primDescs == null) {
1079 return null;
1080 }
1081
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001082 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001083
1084 // If no timestamp is set, default the timestamp to the last timestamp for the device.
1085 if (timestamp == null) {
1086 timestamp = lastTimestamp;
1087 }
1088
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001089 if (timestamp.compareTo(lastTimestamp) <= 0) {
1090 // outdated event ignore
1091 return null;
1092 }
1093 removalRequest.put(deviceId, timestamp);
1094
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001095 Device device = devices.remove(deviceId);
1096 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001097 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1098 if (ports != null) {
1099 ports.clear();
1100 }
1101 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001102 descs.clear();
1103 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001104 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001105 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001106 }
1107
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001108 /**
1109 * Checks if given timestamp is superseded by removal request
1110 * with more recent timestamp.
1111 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001112 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001113 * @param timestampToCheck timestamp of an event to check
1114 * @return true if device is already removed
1115 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001116 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1117 Timestamp removalTimestamp = removalRequest.get(deviceId);
1118 if (removalTimestamp != null &&
Jordan Halterman8a0b3972017-08-15 16:14:18 -07001119 removalTimestamp.compareTo(timestampToCheck) > 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001120 // removalRequest is more recent
1121 return true;
1122 }
1123 return false;
1124 }
1125
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001126 /**
1127 * Returns a Device, merging description given from multiple Providers.
1128 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001129 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001130 * @param providerDescs Collection of Descriptions from multiple providers
1131 * @return Device instance
1132 */
1133 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001134 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001135
Thomas Vachuska444eda62014-10-28 13:09:42 -07001136 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001137
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001138 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001139
1140 DeviceDescriptions desc = providerDescs.get(primary);
1141
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001142 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001143 Type type = base.type();
1144 String manufacturer = base.manufacturer();
1145 String hwVersion = base.hwVersion();
1146 String swVersion = base.swVersion();
1147 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001148 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001149 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1150 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001151
1152 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1153 if (e.getKey().equals(primary)) {
1154 continue;
1155 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001156 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001157 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001158 // Currently assuming there will never be a key conflict between
1159 // providers
1160
1161 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001162 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001163 }
1164
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001165 return new DefaultDevice(primary, deviceId, type, manufacturer,
1166 hwVersion, swVersion, serialNumber,
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001167 chassisId, annotations.build());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001168 }
1169
Marc De Leenheer88194c32015-05-29 22:10:59 -07001170 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1171 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001172 return new DefaultPort(device, number, isEnabled, description.type(),
1173 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001174 }
1175
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001176 /**
1177 * Returns a Port, merging description given from multiple Providers.
1178 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001179 * @param device device the port is on
1180 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001181 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001182 * @return Port instance
1183 */
1184 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001185 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001186
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001187 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001188 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001189 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001190 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001191 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001192 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001193 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1194 if (portDesc != null) {
1195 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001196 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001197 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001198 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001199 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001200 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001201 if (e.getKey().equals(primary)) {
1202 continue;
1203 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001204 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001205 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001206 // Currently assuming there will never be a key conflict between
1207 // providers
1208
1209 // annotation merging. not so efficient, should revisit later
1210 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1211 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001212 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1213 continue;
1214 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001215 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001216 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001217 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001218 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001219 }
1220 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001221 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001222 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001223 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001224 PortDescription current = portDesc.value();
1225 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001226 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001227 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001228 }
1229
1230 /**
1231 * @return primary ProviderID, or randomly chosen one if none exists
1232 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001233 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001234 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001235 ProviderId fallBackPrimary = null;
1236 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1237 if (!e.getKey().isAncillary()) {
1238 return e.getKey();
1239 } else if (fallBackPrimary == null) {
1240 // pick randomly as a fallback in case there is no primary
1241 fallBackPrimary = e.getKey();
1242 }
1243 }
1244 return fallBackPrimary;
1245 }
1246
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001247 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001248 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001249 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001250 return providerDescs.get(pid);
1251 }
1252
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001253 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001254 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001255 }
1256
Jonathan Hart7d656f42015-01-27 14:07:23 -08001257 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001258 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001259 }
Madan Jampani47c93732014-10-06 20:46:08 -07001260
Jonathan Hart7d656f42015-01-27 14:07:23 -08001261 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001262 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001263 }
1264
Palash Kala6c526062018-04-03 18:25:11 +09001265 private void notifyPeers(InternalDeviceStatusChangeEvent event) {
1266 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001267 }
1268
Jonathan Hart7d656f42015-01-27 14:07:23 -08001269 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001270 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001271 }
1272
Jonathan Hart7d656f42015-01-27 14:07:23 -08001273 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001274 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001275 }
1276
Jonathan Hart7d656f42015-01-27 14:07:23 -08001277 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001278 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1279 }
1280
1281 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1282 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001283 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001284 } catch (IOException e) {
1285 log.error("Failed to send" + event + " to " + recipient, e);
1286 }
1287 }
1288
Palash Kala6c526062018-04-03 18:25:11 +09001289 private void notifyPeer(NodeId recipient, InternalDeviceStatusChangeEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001290 try {
Palash Kala6c526062018-04-03 18:25:11 +09001291 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001292 } catch (IOException e) {
1293 log.error("Failed to send" + event + " to " + recipient, e);
1294 }
1295 }
1296
1297 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1298 try {
1299 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1300 } catch (IOException e) {
1301 log.error("Failed to send" + event + " to " + recipient, e);
1302 }
1303 }
1304
1305 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1306 try {
1307 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1308 } catch (IOException e) {
1309 log.error("Failed to send" + event + " to " + recipient, e);
1310 }
1311 }
1312
1313 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1314 try {
1315 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1316 } catch (IOException e) {
1317 log.error("Failed to send" + event + " to " + recipient, e);
1318 }
1319 }
1320
1321 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1322 final NodeId self = clusterService.getLocalNode().id();
1323
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001324 final int numDevices = deviceDescs.size();
1325 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1326 final int portsPerDevice = 8; // random factor to minimize reallocation
1327 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1328 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001329
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001330 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001331
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001332 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001333 synchronized (devDescs) {
1334
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001335 // send device offline timestamp
1336 Timestamp lOffline = this.offline.get(deviceId);
1337 if (lOffline != null) {
1338 adOffline.put(deviceId, lOffline);
1339 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001340
1341 for (Entry<ProviderId, DeviceDescriptions>
1342 prov : devDescs.entrySet()) {
1343
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001344 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001345 final ProviderId provId = prov.getKey();
1346 final DeviceDescriptions descs = prov.getValue();
1347
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001348 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001349 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001350
1351 for (Entry<PortNumber, Timestamped<PortDescription>>
1352 portDesc : descs.getPortDescs().entrySet()) {
1353
1354 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001355 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001356 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001357 }
1358 }
1359 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001360 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001361
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001362 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001363 }
1364
1365 /**
1366 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001367 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001368 * Notify sender about out-dated information using regular replication message.
1369 * Send back advertisement to sender if not in sync.
1370 *
1371 * @param advertisement to respond to
1372 */
1373 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1374
1375 final NodeId sender = advertisement.sender();
1376
1377 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1378 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1379 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1380
1381 // Fragments to request
1382 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1383 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1384
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001385 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001386 final DeviceId deviceId = de.getKey();
1387 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1388
1389 synchronized (lDevice) {
1390 // latestTimestamp across provider
1391 // Note: can be null initially
1392 Timestamp localLatest = offline.get(deviceId);
1393
1394 // handle device Ads
1395 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1396 final ProviderId provId = prov.getKey();
1397 final DeviceDescriptions lDeviceDescs = prov.getValue();
1398
1399 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1400
1401
1402 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1403 Timestamp advDevTimestamp = devAds.get(devFragId);
1404
Jonathan Hart403ea932015-02-20 16:23:00 -08001405 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1406 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001407 // remote does not have it or outdated, suggest
1408 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1409 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1410 // local is outdated, request
1411 reqDevices.add(devFragId);
1412 }
1413
1414 // handle port Ads
1415 for (Entry<PortNumber, Timestamped<PortDescription>>
1416 pe : lDeviceDescs.getPortDescs().entrySet()) {
1417
1418 final PortNumber num = pe.getKey();
1419 final Timestamped<PortDescription> lPort = pe.getValue();
1420
1421 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1422
1423 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001424 if (advPortTimestamp == null || lPort.isNewerThan(
1425 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001426 // remote does not have it or outdated, suggest
1427 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1428 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1429 // local is outdated, request
1430 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1431 reqPorts.add(portFragId);
1432 }
1433
1434 // remove port Ad already processed
1435 portAds.remove(portFragId);
1436 } // end local port loop
1437
1438 // remove device Ad already processed
1439 devAds.remove(devFragId);
1440
1441 // find latest and update
1442 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1443 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001444 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001445 localLatest = providerLatest;
1446 }
1447 } // end local provider loop
1448
1449 // checking if remote timestamp is more recent.
1450 Timestamp rOffline = offlineAds.get(deviceId);
jaegonkim73c21bd2018-01-13 10:52:02 +09001451 if (localLatest == null || (rOffline != null && rOffline.compareTo(localLatest) > 0)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001452 // remote offline timestamp suggests that the
1453 // device is off-line
1454 markOfflineInternal(deviceId, rOffline);
1455 }
1456
1457 Timestamp lOffline = offline.get(deviceId);
1458 if (lOffline != null && rOffline == null) {
1459 // locally offline, but remote is online, suggest offline
Palash Kala6c526062018-04-03 18:25:11 +09001460 notifyPeer(sender, new InternalDeviceStatusChangeEvent(deviceId, lOffline, false));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001461 }
1462
1463 // remove device offline Ad already processed
1464 offlineAds.remove(deviceId);
1465 } // end local device loop
1466 } // device lock
1467
1468 // If there is any Ads left, request them
1469 log.trace("Ads left {}, {}", devAds, portAds);
1470 reqDevices.addAll(devAds.keySet());
1471 reqPorts.addAll(portAds.keySet());
1472
1473 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1474 log.trace("Nothing to request to remote peer {}", sender);
1475 return;
1476 }
1477
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001478 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001479
1480 // 2-way Anti-Entropy for now
1481 try {
1482 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1483 } catch (IOException e) {
1484 log.error("Failed to send response advertisement to " + sender, e);
1485 }
1486
1487// Sketch of 3-way Anti-Entropy
1488// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1489// ClusterMessage message = new ClusterMessage(
1490// clusterService.getLocalNode().id(),
1491// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1492// SERIALIZER.encode(request));
1493//
1494// try {
1495// clusterCommunicator.unicast(message, advertisement.sender());
1496// } catch (IOException e) {
1497// log.error("Failed to send advertisement reply to "
1498// + advertisement.sender(), e);
1499// }
Madan Jampani47c93732014-10-06 20:46:08 -07001500 }
1501
Madan Jampani255a58b2014-10-09 12:08:20 -07001502 private void notifyDelegateIfNotNull(DeviceEvent event) {
1503 if (event != null) {
1504 notifyDelegate(event);
1505 }
1506 }
1507
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001508 private final class SendAdvertisementTask implements Runnable {
1509
1510 @Override
1511 public void run() {
1512 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001513 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001514 return;
1515 }
1516
1517 try {
1518 final NodeId self = clusterService.getLocalNode().id();
1519 Set<ControllerNode> nodes = clusterService.getNodes();
1520
1521 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1522 .transform(toNodeId())
1523 .toList();
1524
1525 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001526 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001527 return;
1528 }
1529
1530 NodeId peer;
1531 do {
1532 int idx = RandomUtils.nextInt(0, nodeIds.size());
1533 peer = nodeIds.get(idx);
1534 } while (peer.equals(self));
1535
1536 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1537
1538 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001539 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001540 return;
1541 }
1542
1543 try {
1544 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1545 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001546 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001547 return;
1548 }
1549 } catch (Exception e) {
1550 // catch all Exception to avoid Scheduled task being suppressed.
1551 log.error("Exception thrown while sending advertisement", e);
1552 }
1553 }
1554 }
1555
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001556 private void handleDeviceEvent(InternalDeviceEvent event) {
1557 ProviderId providerId = event.providerId();
1558 DeviceId deviceId = event.deviceId();
1559 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001560
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001561 try {
1562 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1563 deviceDescription));
1564 } catch (Exception e) {
1565 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001566 }
1567 }
1568
Palash Kala6c526062018-04-03 18:25:11 +09001569 private void handleDeviceStatusChangeEvent(InternalDeviceStatusChangeEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001570 DeviceId deviceId = event.deviceId();
1571 Timestamp timestamp = event.timestamp();
Palash Kala6c526062018-04-03 18:25:11 +09001572 Boolean available = event.available();
Madan Jampani25322532014-10-08 11:20:38 -07001573
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001574 try {
Palash Kala6c526062018-04-03 18:25:11 +09001575 if (available) {
1576 notifyDelegateIfNotNull(markOnlineInternal(deviceId, timestamp));
1577 } else {
1578 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1579 }
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001580 } catch (Exception e) {
Palash Kala6c526062018-04-03 18:25:11 +09001581 log.warn("Exception thrown handling device status change event", 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}