blob: de6d2f023526ab71766e4276c6f12571354461e6 [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 }
Thomas Vachuskae36a2822018-05-03 12:16:52 -0700541 } else {
542 log.warn("Device {} does not exist in store", deviceId);
Palash Kala6c526062018-04-03 18:25:11 +0900543 }
Palash Kala6c526062018-04-03 18:25:11 +0900544 return null;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700545 }
546
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700547 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700548 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700549 DeviceId deviceId,
550 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700551
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800552 NodeId localNode = clusterService.getLocalNode().id();
553 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
554 // since it will trigger distributed store read.
555 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
556 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
557 // If we don't care much about topology performance, then it might be OK.
558 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700559
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800560 // Process port update only if we're the master of the device,
561 // otherwise signal the actual master.
562 List<DeviceEvent> deviceEvents = null;
563 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700564
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800565 final Timestamp newTimestamp;
566 try {
567 newTimestamp = deviceClockService.getTimestamp(deviceId);
568 } catch (IllegalStateException e) {
569 log.info("Timestamp was not available for device {}", deviceId);
570 log.debug(" discarding {}", portDescriptions);
571 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700572
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800573 // Possible situation:
574 // Device connected and became master for short period of time,
575 // but lost mastership before this instance had the chance to
576 // retrieve term information.
577
578 // Information dropped here is expected to be recoverable by
579 // device probing after mastership change
580
581 return Collections.emptyList();
582 }
583 log.debug("timestamp for {} {}", deviceId, newTimestamp);
584
585 final Timestamped<List<PortDescription>> timestampedInput
586 = new Timestamped<>(portDescriptions, newTimestamp);
587 final Timestamped<List<PortDescription>> merged;
588
589 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
590
591 synchronized (device) {
592 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
593 final DeviceDescriptions descs = device.get(providerId);
594 List<PortDescription> mergedList =
595 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700596 .transform(input ->
597 // lookup merged port description
598 descs.getPortDesc(input.portNumber()).value()
599 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700600 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800601 }
602
603 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700604 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700605 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800606 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
607 }
608
609 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700610 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700611 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700612
Ray Milkeyfe0e0852018-01-18 11:14:05 -0800613 return deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700614 }
615
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700616 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700617 DeviceId deviceId,
618 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700619
620 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700621 if (device == null) {
622 log.debug("Device is no longer valid: {}", deviceId);
623 return Collections.emptyList();
624 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700625
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700626 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700627 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
628
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700629 List<DeviceEvent> events = new ArrayList<>();
630 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700631
632 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
633 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700634 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700635 }
636
637 DeviceDescriptions descs = descsMap.get(providerId);
638 // every provider must provide DeviceDescription.
639 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700640 "Device description for Device ID %s from Provider %s was not found",
641 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700642
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700643 Map<PortNumber, Port> ports = getPortMap(deviceId);
644
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700645 final Timestamp newTimestamp = portDescriptions.timestamp();
646
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700647 // Add new ports
648 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700649 for (PortDescription portDescription : portDescriptions.value()) {
650 final PortNumber number = portDescription.portNumber();
651 processed.add(number);
652
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700653 final Port oldPort = ports.get(number);
654 final Port newPort;
Palash Kala8d30b612018-03-02 11:06:10 +0900655 boolean isRemoved = portDescription.isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700656
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700657
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700658 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
659 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700660 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700661 // on new port or valid update
662 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700663 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700664 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700665 newPort = composePort(device, number, descsMap);
666 } else {
667 // outdated event, ignored.
668 continue;
669 }
670
Palash Kala8d30b612018-03-02 11:06:10 +0900671 if (isRemoved && oldPort != null) {
672 events.add(removePort(deviceId, oldPort.number()));
673 } else if (!isRemoved) {
674 events.add(oldPort == null ?
675 createPort(device, newPort, ports) :
676 updatePort(device, oldPort, newPort, ports));
677 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700678 }
679
680 events.addAll(pruneOldPorts(device, ports, processed));
681 }
682 return FluentIterable.from(events).filter(notNull()).toList();
683 }
684
685 // Creates a new port based on the port description adds it to the map and
686 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700687 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700688 private DeviceEvent createPort(Device device, Port newPort,
689 Map<PortNumber, Port> ports) {
690 ports.put(newPort.number(), newPort);
691 return new DeviceEvent(PORT_ADDED, device, newPort);
692 }
693
694 // Checks if the specified port requires update and if so, it replaces the
695 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700696 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700697 private DeviceEvent updatePort(Device device, Port oldPort,
698 Port newPort,
699 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100700
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700701 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700702 oldPort.type() != newPort.type() ||
703 oldPort.portSpeed() != newPort.portSpeed() ||
704 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700705 ports.put(oldPort.number(), newPort);
706 return new DeviceEvent(PORT_UPDATED, device, newPort);
707 }
708 return null;
709 }
710
Michal Machce774332017-01-25 11:02:55 +0100711 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
712
713 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
714 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
715
716 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
717 }
718
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700719 // Prunes the specified list of ports based on which ports are in the
720 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700721 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700722 private List<DeviceEvent> pruneOldPorts(Device device,
723 Map<PortNumber, Port> ports,
724 Set<PortNumber> processed) {
725 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700726 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700727 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700728 Entry<PortNumber, Port> e = iterator.next();
729 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700730 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700731 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700732 iterator.remove();
733 }
734 }
735 return events;
736 }
737
738 // Gets the map of ports for the specified device; if one does not already
739 // exist, it creates and registers a new one.
740 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700741 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700742 }
743
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700744 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700745 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700746 Map<ProviderId, DeviceDescriptions> r;
747 r = deviceDescs.get(deviceId);
748 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700749 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700750 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
751 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
752 if (concurrentlyAdded != null) {
753 r = concurrentlyAdded;
754 }
755 }
756 return r;
757 }
758
759 // Guarded by deviceDescs value (=Device lock)
760 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
761 Map<ProviderId, DeviceDescriptions> device,
762 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700763 synchronized (device) {
764 DeviceDescriptions r = device.get(providerId);
765 if (r == null) {
766 r = new DeviceDescriptions(deltaDesc);
767 device.put(providerId, r);
768 }
769 return r;
770 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700771 }
772
773 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700774 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
775 DeviceId deviceId,
776 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700777 final Timestamp newTimestamp;
778 try {
779 newTimestamp = deviceClockService.getTimestamp(deviceId);
780 } catch (IllegalStateException e) {
781 log.info("Timestamp was not available for device {}", deviceId);
782 log.debug(" discarding {}", portDescription);
783 // Failed to generate timestamp. Ignoring.
784 // See updatePorts comment
785 return null;
786 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700787 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700788 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700789 final DeviceEvent event;
790 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800791 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
792 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700793 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800794 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700795 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700796 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700797 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700798 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700799 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800800 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700801 }
802 return event;
803 }
804
805 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700806 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700807 Device device = devices.get(deviceId);
808 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
809
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700810 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700811 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
812
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700813 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700814
815 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
816 log.debug("Ignoring outdated event: {}", deltaDesc);
817 return null;
818 }
819
820 DeviceDescriptions descs = descsMap.get(providerId);
821 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700822 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700823 "Device description for Device ID %s from Provider %s was not found",
824 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700825
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700826 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
827 final PortNumber number = deltaDesc.value().portNumber();
828 final Port oldPort = ports.get(number);
829 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700830 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100831 boolean toDelete = false;
832
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700833 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700834 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700835 // on new port or valid update
836 // update description
837 descs.putPortDesc(deltaDesc);
838 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100839 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700840 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700841 // same or outdated event, ignored.
842 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700843 return null;
844 }
845
846 if (oldPort == null) {
847 return createPort(device, newPort, ports);
848 } else {
Michal Machce774332017-01-25 11:02:55 +0100849 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700850 }
851 }
852 }
853
854 @Override
855 public List<Port> getPorts(DeviceId deviceId) {
856 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
857 if (ports == null) {
858 return Collections.emptyList();
859 }
860 return ImmutableList.copyOf(ports.values());
861 }
862
863 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700864 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
865 DeviceId deviceId) {
866 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
867 if (descs == null) {
Donghyeok Ho6de4fb92018-01-31 11:04:19 +0900868 return Stream.empty();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700869 }
870 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
871 final Optional<DeviceDescriptions> devDescs;
872 synchronized (descs) {
873 devDescs = Optional.ofNullable(descs.get(pid));
874 }
875 // DeviceDescriptions is concurrent access-safe
876 return devDescs
877 .map(dd -> dd.getPortDescs().values().stream()
878 .map(Timestamped::value))
879 .orElse(Stream.empty());
880 }
881
882 @Override
sangho538108b2015-04-08 14:29:20 -0700883 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200884 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700885
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200886 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
887 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
888 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
889
890 if (prvStatsMap != null) {
891 for (PortStatistics newStats : newStatsCollection) {
892 PortNumber port = PortNumber.portNumber(newStats.port());
893 PortStatistics prvStats = prvStatsMap.get(port);
894 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
895 PortStatistics deltaStats = builder.build();
896 if (prvStats != null) {
897 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
898 }
899 deltaStatsMap.put(port, deltaStats);
900 newStatsMap.put(port, newStats);
901 }
902 } else {
903 for (PortStatistics newStats : newStatsCollection) {
904 PortNumber port = PortNumber.portNumber(newStats.port());
905 newStatsMap.put(port, newStats);
906 }
sangho538108b2015-04-08 14:29:20 -0700907 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200908 devicePortDeltaStats.put(deviceId, deltaStatsMap);
909 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200910 // DeviceEvent returns null because of InternalPortStatsListener usage
911 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200912 }
913
914 /**
915 * Calculate delta statistics by subtracting previous from new statistics.
916 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700917 * @param deviceId device identifier
918 * @param prvStats previous port statistics
919 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200920 * @return PortStatistics
921 */
922 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
923 // calculate time difference
924 long deltaStatsSec, deltaStatsNano;
925 if (newStats.durationNano() < prvStats.durationNano()) {
926 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
927 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
928 } else {
929 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
930 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
931 }
932 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
933 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
934 .setPort(newStats.port())
935 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
936 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
937 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
938 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
939 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
940 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
941 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
942 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
943 .setDurationSec(deltaStatsSec)
944 .setDurationNano(deltaStatsNano)
945 .build();
946 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700947 }
948
949 @Override
950 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700951 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
952 if (portStats == null) {
953 return Collections.emptyList();
954 }
955 return ImmutableList.copyOf(portStats.values());
956 }
957
958 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530959 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
960 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
961 if (portStatsMap == null) {
962 return null;
963 }
964 PortStatistics portStats = portStatsMap.get(portNumber);
965 return portStats;
966 }
967
968 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200969 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
970 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
971 if (portStats == null) {
972 return Collections.emptyList();
973 }
974 return ImmutableList.copyOf(portStats.values());
975 }
976
977 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530978 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
979 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
980 if (portStatsMap == null) {
981 return null;
982 }
983 PortStatistics portStats = portStatsMap.get(portNumber);
984 return portStats;
985 }
986
987 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700988 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
989 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
990 return ports == null ? null : ports.get(portNumber);
991 }
992
993 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700994 public PortDescription getPortDescription(ProviderId pid,
995 DeviceId deviceId,
996 PortNumber portNumber) {
997 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
998 if (descs == null) {
999 return null;
1000 }
1001 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1002 final Optional<DeviceDescriptions> devDescs;
1003 synchronized (descs) {
1004 devDescs = Optional.ofNullable(descs.get(pid));
1005 }
1006 // DeviceDescriptions is concurrent access-safe
1007 return devDescs
1008 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1009 .map(Timestamped::value)
1010 .orElse(null);
1011 }
1012
1013 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001014 public boolean isAvailable(DeviceId deviceId) {
1015 return availableDevices.contains(deviceId);
1016 }
1017
1018 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001019 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001020 final NodeId myId = clusterService.getLocalNode().id();
1021 NodeId master = mastershipService.getMasterFor(deviceId);
1022
1023 // if there exist a master, forward
1024 // if there is no master, try to become one and process
1025
1026 boolean relinquishAtEnd = false;
1027 if (master == null) {
1028 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1029 if (myRole != MastershipRole.NONE) {
1030 relinquishAtEnd = true;
1031 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001032 log.debug("Temporarily requesting role for {} to remove", deviceId);
Jordan Haltermanf1c602d2017-10-18 11:26:52 -07001033 if (mastershipService.requestRoleFor(deviceId).join() == MastershipRole.MASTER) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001034 master = myId;
1035 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001036 }
1037
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001038 boolean isMaster = myId.equals(master);
1039
1040 // If this node is not the master, forward the request.
1041 if (!isMaster) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001042 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001043 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001044
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001045 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001046 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001047 /* error log:
1048 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1049 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001050 }
1051
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001052 // If this node is the master, get a timestamp. Otherwise, default to the current device timestamp.
1053 Timestamp timestamp = isMaster ? deviceClockService.getTimestamp(deviceId) : null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001054
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001055 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001056
1057 // If this node is the master, update peers.
1058 if (isMaster && event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001059 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001060 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001061 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001062 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001063
1064 // Relinquish mastership if acquired to remove the device.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001065 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001066 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001067 mastershipService.relinquishMastership(deviceId);
1068 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001069 return event;
1070 }
1071
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001072 private DeviceEvent removeDeviceInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001073
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001074 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001075 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001076 // accept removal request if given timestamp is newer than
1077 // the latest Timestamp from Primary provider
1078 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001079 if (primDescs == null) {
1080 return null;
1081 }
1082
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001083 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001084
1085 // If no timestamp is set, default the timestamp to the last timestamp for the device.
1086 if (timestamp == null) {
1087 timestamp = lastTimestamp;
1088 }
1089
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001090 if (timestamp.compareTo(lastTimestamp) <= 0) {
1091 // outdated event ignore
1092 return null;
1093 }
1094 removalRequest.put(deviceId, timestamp);
1095
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001096 Device device = devices.remove(deviceId);
1097 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001098 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1099 if (ports != null) {
1100 ports.clear();
1101 }
1102 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001103 descs.clear();
1104 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001105 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001106 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001107 }
1108
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001109 /**
1110 * Checks if given timestamp is superseded by removal request
1111 * with more recent timestamp.
1112 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001113 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001114 * @param timestampToCheck timestamp of an event to check
1115 * @return true if device is already removed
1116 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001117 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1118 Timestamp removalTimestamp = removalRequest.get(deviceId);
1119 if (removalTimestamp != null &&
Jordan Halterman8a0b3972017-08-15 16:14:18 -07001120 removalTimestamp.compareTo(timestampToCheck) > 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001121 // removalRequest is more recent
1122 return true;
1123 }
1124 return false;
1125 }
1126
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001127 /**
1128 * Returns a Device, merging description given from multiple Providers.
1129 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001130 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001131 * @param providerDescs Collection of Descriptions from multiple providers
1132 * @return Device instance
1133 */
1134 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001135 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001136
Thomas Vachuska444eda62014-10-28 13:09:42 -07001137 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001138
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001139 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001140
1141 DeviceDescriptions desc = providerDescs.get(primary);
1142
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001143 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001144 Type type = base.type();
1145 String manufacturer = base.manufacturer();
1146 String hwVersion = base.hwVersion();
1147 String swVersion = base.swVersion();
1148 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001149 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001150 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1151 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001152
1153 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1154 if (e.getKey().equals(primary)) {
1155 continue;
1156 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001157 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001158 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001159 // Currently assuming there will never be a key conflict between
1160 // providers
1161
1162 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001163 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001164 }
1165
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001166 return new DefaultDevice(primary, deviceId, type, manufacturer,
1167 hwVersion, swVersion, serialNumber,
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001168 chassisId, annotations.build());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001169 }
1170
Marc De Leenheer88194c32015-05-29 22:10:59 -07001171 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1172 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001173 return new DefaultPort(device, number, isEnabled, description.type(),
1174 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001175 }
1176
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001177 /**
1178 * Returns a Port, merging description given from multiple Providers.
1179 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001180 * @param device device the port is on
1181 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001182 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001183 * @return Port instance
1184 */
1185 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001186 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001187
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001188 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001189 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001190 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001191 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001192 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001193 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001194 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1195 if (portDesc != null) {
1196 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001197 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001198 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001199 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001200 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001201 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001202 if (e.getKey().equals(primary)) {
1203 continue;
1204 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001205 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001206 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001207 // Currently assuming there will never be a key conflict between
1208 // providers
1209
1210 // annotation merging. not so efficient, should revisit later
1211 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1212 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001213 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1214 continue;
1215 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001216 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001217 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001218 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001219 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001220 }
1221 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001222 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001223 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001224 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001225 PortDescription current = portDesc.value();
1226 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001227 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001228 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001229 }
1230
1231 /**
1232 * @return primary ProviderID, or randomly chosen one if none exists
1233 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001234 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001235 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001236 ProviderId fallBackPrimary = null;
1237 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1238 if (!e.getKey().isAncillary()) {
1239 return e.getKey();
1240 } else if (fallBackPrimary == null) {
1241 // pick randomly as a fallback in case there is no primary
1242 fallBackPrimary = e.getKey();
1243 }
1244 }
1245 return fallBackPrimary;
1246 }
1247
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001248 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001249 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001250 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001251 return providerDescs.get(pid);
1252 }
1253
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001254 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001255 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001256 }
1257
Jonathan Hart7d656f42015-01-27 14:07:23 -08001258 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001259 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001260 }
Madan Jampani47c93732014-10-06 20:46:08 -07001261
Jonathan Hart7d656f42015-01-27 14:07:23 -08001262 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001263 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001264 }
1265
Palash Kala6c526062018-04-03 18:25:11 +09001266 private void notifyPeers(InternalDeviceStatusChangeEvent event) {
1267 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001268 }
1269
Jonathan Hart7d656f42015-01-27 14:07:23 -08001270 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001271 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001272 }
1273
Jonathan Hart7d656f42015-01-27 14:07:23 -08001274 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001275 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001276 }
1277
Jonathan Hart7d656f42015-01-27 14:07:23 -08001278 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001279 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1280 }
1281
1282 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1283 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001284 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001285 } catch (IOException e) {
1286 log.error("Failed to send" + event + " to " + recipient, e);
1287 }
1288 }
1289
Palash Kala6c526062018-04-03 18:25:11 +09001290 private void notifyPeer(NodeId recipient, InternalDeviceStatusChangeEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001291 try {
Palash Kala6c526062018-04-03 18:25:11 +09001292 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001293 } catch (IOException e) {
1294 log.error("Failed to send" + event + " to " + recipient, e);
1295 }
1296 }
1297
1298 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1299 try {
1300 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1301 } catch (IOException e) {
1302 log.error("Failed to send" + event + " to " + recipient, e);
1303 }
1304 }
1305
1306 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1307 try {
1308 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1309 } catch (IOException e) {
1310 log.error("Failed to send" + event + " to " + recipient, e);
1311 }
1312 }
1313
1314 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1315 try {
1316 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1317 } catch (IOException e) {
1318 log.error("Failed to send" + event + " to " + recipient, e);
1319 }
1320 }
1321
1322 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1323 final NodeId self = clusterService.getLocalNode().id();
1324
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001325 final int numDevices = deviceDescs.size();
1326 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1327 final int portsPerDevice = 8; // random factor to minimize reallocation
1328 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1329 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001330
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001331 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001332
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001333 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001334 synchronized (devDescs) {
1335
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001336 // send device offline timestamp
1337 Timestamp lOffline = this.offline.get(deviceId);
1338 if (lOffline != null) {
1339 adOffline.put(deviceId, lOffline);
1340 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001341
1342 for (Entry<ProviderId, DeviceDescriptions>
1343 prov : devDescs.entrySet()) {
1344
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001345 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001346 final ProviderId provId = prov.getKey();
1347 final DeviceDescriptions descs = prov.getValue();
1348
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001349 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001350 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001351
1352 for (Entry<PortNumber, Timestamped<PortDescription>>
1353 portDesc : descs.getPortDescs().entrySet()) {
1354
1355 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001356 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001357 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001358 }
1359 }
1360 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001361 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001362
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001363 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001364 }
1365
1366 /**
1367 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001368 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001369 * Notify sender about out-dated information using regular replication message.
1370 * Send back advertisement to sender if not in sync.
1371 *
1372 * @param advertisement to respond to
1373 */
1374 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1375
1376 final NodeId sender = advertisement.sender();
1377
1378 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1379 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1380 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1381
1382 // Fragments to request
1383 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1384 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1385
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001386 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001387 final DeviceId deviceId = de.getKey();
1388 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1389
1390 synchronized (lDevice) {
1391 // latestTimestamp across provider
1392 // Note: can be null initially
1393 Timestamp localLatest = offline.get(deviceId);
1394
1395 // handle device Ads
1396 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1397 final ProviderId provId = prov.getKey();
1398 final DeviceDescriptions lDeviceDescs = prov.getValue();
1399
1400 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1401
1402
1403 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1404 Timestamp advDevTimestamp = devAds.get(devFragId);
1405
Jonathan Hart403ea932015-02-20 16:23:00 -08001406 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1407 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001408 // remote does not have it or outdated, suggest
1409 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1410 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1411 // local is outdated, request
1412 reqDevices.add(devFragId);
1413 }
1414
1415 // handle port Ads
1416 for (Entry<PortNumber, Timestamped<PortDescription>>
1417 pe : lDeviceDescs.getPortDescs().entrySet()) {
1418
1419 final PortNumber num = pe.getKey();
1420 final Timestamped<PortDescription> lPort = pe.getValue();
1421
1422 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1423
1424 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001425 if (advPortTimestamp == null || lPort.isNewerThan(
1426 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001427 // remote does not have it or outdated, suggest
1428 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1429 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1430 // local is outdated, request
1431 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1432 reqPorts.add(portFragId);
1433 }
1434
1435 // remove port Ad already processed
1436 portAds.remove(portFragId);
1437 } // end local port loop
1438
1439 // remove device Ad already processed
1440 devAds.remove(devFragId);
1441
1442 // find latest and update
1443 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1444 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001445 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001446 localLatest = providerLatest;
1447 }
1448 } // end local provider loop
1449
1450 // checking if remote timestamp is more recent.
1451 Timestamp rOffline = offlineAds.get(deviceId);
jaegonkim73c21bd2018-01-13 10:52:02 +09001452 if (localLatest == null || (rOffline != null && rOffline.compareTo(localLatest) > 0)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001453 // remote offline timestamp suggests that the
1454 // device is off-line
1455 markOfflineInternal(deviceId, rOffline);
1456 }
1457
1458 Timestamp lOffline = offline.get(deviceId);
1459 if (lOffline != null && rOffline == null) {
1460 // locally offline, but remote is online, suggest offline
Palash Kala6c526062018-04-03 18:25:11 +09001461 notifyPeer(sender, new InternalDeviceStatusChangeEvent(deviceId, lOffline, false));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001462 }
1463
1464 // remove device offline Ad already processed
1465 offlineAds.remove(deviceId);
1466 } // end local device loop
1467 } // device lock
1468
1469 // If there is any Ads left, request them
1470 log.trace("Ads left {}, {}", devAds, portAds);
1471 reqDevices.addAll(devAds.keySet());
1472 reqPorts.addAll(portAds.keySet());
1473
1474 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1475 log.trace("Nothing to request to remote peer {}", sender);
1476 return;
1477 }
1478
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001479 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001480
1481 // 2-way Anti-Entropy for now
1482 try {
1483 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1484 } catch (IOException e) {
1485 log.error("Failed to send response advertisement to " + sender, e);
1486 }
1487
1488// Sketch of 3-way Anti-Entropy
1489// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1490// ClusterMessage message = new ClusterMessage(
1491// clusterService.getLocalNode().id(),
1492// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1493// SERIALIZER.encode(request));
1494//
1495// try {
1496// clusterCommunicator.unicast(message, advertisement.sender());
1497// } catch (IOException e) {
1498// log.error("Failed to send advertisement reply to "
1499// + advertisement.sender(), e);
1500// }
Madan Jampani47c93732014-10-06 20:46:08 -07001501 }
1502
Madan Jampani255a58b2014-10-09 12:08:20 -07001503 private void notifyDelegateIfNotNull(DeviceEvent event) {
1504 if (event != null) {
1505 notifyDelegate(event);
1506 }
1507 }
1508
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001509 private final class SendAdvertisementTask implements Runnable {
1510
1511 @Override
1512 public void run() {
1513 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001514 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001515 return;
1516 }
1517
1518 try {
1519 final NodeId self = clusterService.getLocalNode().id();
1520 Set<ControllerNode> nodes = clusterService.getNodes();
1521
1522 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1523 .transform(toNodeId())
1524 .toList();
1525
1526 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001527 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001528 return;
1529 }
1530
1531 NodeId peer;
1532 do {
1533 int idx = RandomUtils.nextInt(0, nodeIds.size());
1534 peer = nodeIds.get(idx);
1535 } while (peer.equals(self));
1536
1537 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1538
1539 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001540 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001541 return;
1542 }
1543
1544 try {
1545 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1546 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001547 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001548 return;
1549 }
1550 } catch (Exception e) {
1551 // catch all Exception to avoid Scheduled task being suppressed.
1552 log.error("Exception thrown while sending advertisement", e);
1553 }
1554 }
1555 }
1556
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001557 private void handleDeviceEvent(InternalDeviceEvent event) {
1558 ProviderId providerId = event.providerId();
1559 DeviceId deviceId = event.deviceId();
1560 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001561
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001562 try {
1563 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1564 deviceDescription));
1565 } catch (Exception e) {
1566 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001567 }
1568 }
1569
Palash Kala6c526062018-04-03 18:25:11 +09001570 private void handleDeviceStatusChangeEvent(InternalDeviceStatusChangeEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001571 DeviceId deviceId = event.deviceId();
1572 Timestamp timestamp = event.timestamp();
Palash Kala6c526062018-04-03 18:25:11 +09001573 Boolean available = event.available();
Madan Jampani25322532014-10-08 11:20:38 -07001574
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001575 try {
Palash Kala6c526062018-04-03 18:25:11 +09001576 if (available) {
1577 notifyDelegateIfNotNull(markOnlineInternal(deviceId, timestamp));
1578 } else {
1579 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1580 }
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001581 } catch (Exception e) {
Palash Kala6c526062018-04-03 18:25:11 +09001582 log.warn("Exception thrown handling device status change event", e);
Madan Jampani25322532014-10-08 11:20:38 -07001583 }
1584 }
1585
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001586 private void handleRemoveRequest(DeviceId did) {
1587 try {
Jayasree Ghosh7d96d6a2017-02-27 18:35:32 +05301588 DeviceEvent event = removeDevice(did);
1589 notifyDelegateIfNotNull(event);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001590 } catch (Exception e) {
1591 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001592 }
1593 }
1594
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001595 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1596 DeviceId deviceId = event.deviceId();
1597 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001598
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001599 try {
1600 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1601 } catch (Exception e) {
1602 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001603 }
1604 }
1605
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001606 private void handlePortEvent(InternalPortEvent event) {
1607 ProviderId providerId = event.providerId();
1608 DeviceId deviceId = event.deviceId();
1609 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001610
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001611 if (getDevice(deviceId) == null) {
1612 log.debug("{} not found on this node yet, ignoring.", deviceId);
1613 // Note: dropped information will be recovered by anti-entropy
1614 return;
1615 }
Madan Jampani47c93732014-10-06 20:46:08 -07001616
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001617 try {
1618 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1619 } catch (Exception e) {
1620 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001621 }
1622 }
1623
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001624 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1625 ProviderId providerId = event.providerId();
1626 DeviceId deviceId = event.deviceId();
1627 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001628
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001629 if (getDevice(deviceId) == null) {
1630 log.debug("{} not found on this node yet, ignoring.", deviceId);
1631 // Note: dropped information will be recovered by anti-entropy
1632 return;
1633 }
Madan Jampani47c93732014-10-06 20:46:08 -07001634
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001635 try {
1636 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1637 } catch (Exception e) {
1638 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001639 }
1640 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001641
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001642 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1643 try {
1644 handleAdvertisement(advertisement);
1645 } catch (Exception e) {
1646 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001647 }
1648 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001649
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001650 private class InternalPortStatsListener
1651 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1652 @Override
1653 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1654 if (event.type() == PUT) {
1655 Device device = devices.get(event.key());
1656 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001657 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001658 }
1659 }
1660 }
1661 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001662}