blob: df59f17cff1607dfba13ee047e6a5340fce6ba90 [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 }
Thomas Vachuskaf131e592018-05-07 11:52:14 -0700365
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700366 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700367 // REGISTER
368 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700369 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700370 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700371 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700372 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700373 } else {
374 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700375 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
376 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700377 }
378 }
379 }
380
381 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700382 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700383 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700384 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700385
386 // update composed device cache
387 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
388 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700389 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
390 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700391
392 if (!providerId.isAncillary()) {
Palash Kala6c526062018-04-03 18:25:11 +0900393 markOnline(newDevice.id(), timestamp, false);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700394 }
395
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700396 log.debug("Device {} added", newDevice.id());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700397 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
398 }
399
400 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700401 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700402 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700403 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700404 Device newDevice, Timestamp newTimestamp,
405 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700406 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700407 boolean propertiesChanged =
408 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700409 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
mskala4b2081a2017-06-12 16:39:50 +0200410 !Objects.equals(oldDevice.providerId(), newDevice.providerId()) ||
411 !Objects.equals(oldDevice.chassisId(), newDevice.chassisId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700412 boolean annotationsChanged =
413 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700414
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700415 // Primary providers can respond to all changes, but ancillary ones
416 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800417 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700418 if ((providerId.isAncillary() && annotationsChanged) ||
419 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700420 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
421 if (!replaced) {
422 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700423 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800424 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700425 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700426
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700427 log.debug("Device {} updated", newDevice.id());
alshabibdc5d8bd2015-11-02 15:41:29 -0800428 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700429 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800430
helenyrwufd296b62016-06-22 17:43:02 -0700431 if (!providerId.isAncillary() && forceAvailable) {
Palash Kala6c526062018-04-03 18:25:11 +0900432 notifyDelegateIfNotNull(markOnline(newDevice.id(), newTimestamp, false));
alshabibdc5d8bd2015-11-02 15:41:29 -0800433 }
434 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700435 }
436
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700437 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700438 // update composed device cache
439 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
440 verify(oldDevice == null,
441 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
442 providerId, oldDevice, newDevice);
443
444 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700445 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700446 }
447
448 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
449 }
450
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700451 @Override
452 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700453 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
454 }
455
456 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700457 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700458 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700459 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700460 deviceId, timestamp);
Palash Kala6c526062018-04-03 18:25:11 +0900461 notifyPeers(new InternalDeviceStatusChangeEvent(deviceId, timestamp, false));
Madan Jampani25322532014-10-08 11:20:38 -0700462 }
463 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700464 }
465
466 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700467 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700468 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700469
470 // locking device
471 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700472 // accept off-line if given timestamp is newer than
473 // the latest Timestamp from Primary provider
474 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
jaegonkim73c21bd2018-01-13 10:52:02 +0900475 if (primDescs != null) {
476 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
477 if (lastTimestamp == null) {
478 lastTimestamp = deviceClockService.getTimestamp(deviceId);
479 }
480 if (timestamp.compareTo(lastTimestamp) <= 0) {
481 // outdated event ignore
482 return null;
483 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700484 }
485
486 offline.put(deviceId, timestamp);
487
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700488 Device device = devices.get(deviceId);
489 if (device == null) {
490 return null;
491 }
492 boolean removed = availableDevices.remove(deviceId);
493 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700494 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700495 }
496 return null;
497 }
498 }
499
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700500 @Override
Palash Kala6c526062018-04-03 18:25:11 +0900501 public DeviceEvent markOnline(DeviceId deviceId) {
502 return markOnline(deviceId, deviceClockService.getTimestamp(deviceId), true);
helenyrwufd296b62016-06-22 17:43:02 -0700503 }
504
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700505 /**
506 * Marks the device as available if the given timestamp is not outdated,
507 * compared to the time the device has been marked offline.
508 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700509 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700510 * @param timestamp of the event triggering this change.
Palash Kala6c526062018-04-03 18:25:11 +0900511 * @param notifyPeers if the event needs to be notified to peers.
512 * @return ready to send event describing what occurred; null if no change
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700513 */
Palash Kala6c526062018-04-03 18:25:11 +0900514 private DeviceEvent markOnline(DeviceId deviceId, Timestamp timestamp, boolean notifyPeers) {
515 final DeviceEvent event = markOnlineInternal(deviceId, timestamp);
516 if (event != null && notifyPeers) {
517 log.debug("Notifying peers of a device online topology event for deviceId: {} {}",
518 deviceId, timestamp);
519 notifyPeers(new InternalDeviceStatusChangeEvent(deviceId, timestamp, true));
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700520 }
Palash Kala6c526062018-04-03 18:25:11 +0900521 return event;
522 }
523
524 // Guarded by deviceDescs value (=Device lock)
525 private DeviceEvent markOnlineInternal(DeviceId deviceId, Timestamp timestamp) {
526 if (devices.containsKey(deviceId)) {
527 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
528 synchronized (deviceLock) {
529 // accept on-line if given timestamp is newer than
530 // the latest offline request Timestamp
531 Timestamp offlineTimestamp = offline.get(deviceId);
532 if (offlineTimestamp == null ||
533 offlineTimestamp.compareTo(timestamp) < 0) {
534 offline.remove(deviceId);
535 Device device = devices.get(deviceId);
536 boolean add = availableDevices.add(deviceId);
537 if (add) {
538 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
539 }
540 }
541 }
Thomas Vachuskae36a2822018-05-03 12:16:52 -0700542 } else {
543 log.warn("Device {} does not exist in store", deviceId);
Palash Kala6c526062018-04-03 18:25:11 +0900544 }
Palash Kala6c526062018-04-03 18:25:11 +0900545 return null;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700546 }
547
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700548 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700549 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700550 DeviceId deviceId,
551 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700552
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800553 NodeId localNode = clusterService.getLocalNode().id();
554 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
555 // since it will trigger distributed store read.
556 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
557 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
558 // If we don't care much about topology performance, then it might be OK.
559 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700560
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800561 // Process port update only if we're the master of the device,
562 // otherwise signal the actual master.
563 List<DeviceEvent> deviceEvents = null;
564 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700565
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800566 final Timestamp newTimestamp;
567 try {
568 newTimestamp = deviceClockService.getTimestamp(deviceId);
569 } catch (IllegalStateException e) {
570 log.info("Timestamp was not available for device {}", deviceId);
571 log.debug(" discarding {}", portDescriptions);
572 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700573
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800574 // Possible situation:
575 // Device connected and became master for short period of time,
576 // but lost mastership before this instance had the chance to
577 // retrieve term information.
578
579 // Information dropped here is expected to be recoverable by
580 // device probing after mastership change
581
582 return Collections.emptyList();
583 }
584 log.debug("timestamp for {} {}", deviceId, newTimestamp);
585
586 final Timestamped<List<PortDescription>> timestampedInput
587 = new Timestamped<>(portDescriptions, newTimestamp);
588 final Timestamped<List<PortDescription>> merged;
589
590 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
591
592 synchronized (device) {
593 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
594 final DeviceDescriptions descs = device.get(providerId);
595 List<PortDescription> mergedList =
596 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700597 .transform(input ->
598 // lookup merged port description
599 descs.getPortDesc(input.portNumber()).value()
600 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700601 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800602 }
603
604 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700605 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700606 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800607 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
608 }
609
610 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700611 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700612 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700613
Ray Milkeyfe0e0852018-01-18 11:14:05 -0800614 return deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700615 }
616
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700617 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700618 DeviceId deviceId,
619 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700620
621 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700622 if (device == null) {
623 log.debug("Device is no longer valid: {}", deviceId);
624 return Collections.emptyList();
625 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700626
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700627 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700628 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
629
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700630 List<DeviceEvent> events = new ArrayList<>();
631 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700632
633 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
634 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700635 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700636 }
637
638 DeviceDescriptions descs = descsMap.get(providerId);
639 // every provider must provide DeviceDescription.
640 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700641 "Device description for Device ID %s from Provider %s was not found",
642 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700643
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700644 Map<PortNumber, Port> ports = getPortMap(deviceId);
645
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700646 final Timestamp newTimestamp = portDescriptions.timestamp();
647
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700648 // Add new ports
649 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700650 for (PortDescription portDescription : portDescriptions.value()) {
651 final PortNumber number = portDescription.portNumber();
652 processed.add(number);
653
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700654 final Port oldPort = ports.get(number);
655 final Port newPort;
Palash Kala8d30b612018-03-02 11:06:10 +0900656 boolean isRemoved = portDescription.isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700657
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700658
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700659 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
660 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700661 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700662 // on new port or valid update
663 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700664 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700665 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700666 newPort = composePort(device, number, descsMap);
667 } else {
668 // outdated event, ignored.
669 continue;
670 }
671
Palash Kala8d30b612018-03-02 11:06:10 +0900672 if (isRemoved && oldPort != null) {
673 events.add(removePort(deviceId, oldPort.number()));
674 } else if (!isRemoved) {
675 events.add(oldPort == null ?
676 createPort(device, newPort, ports) :
677 updatePort(device, oldPort, newPort, ports));
678 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700679 }
680
681 events.addAll(pruneOldPorts(device, ports, processed));
682 }
683 return FluentIterable.from(events).filter(notNull()).toList();
684 }
685
686 // Creates a new port based on the port description adds it to the map and
687 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700688 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700689 private DeviceEvent createPort(Device device, Port newPort,
690 Map<PortNumber, Port> ports) {
691 ports.put(newPort.number(), newPort);
692 return new DeviceEvent(PORT_ADDED, device, newPort);
693 }
694
695 // Checks if the specified port requires update and if so, it replaces the
696 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700697 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700698 private DeviceEvent updatePort(Device device, Port oldPort,
699 Port newPort,
700 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100701
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700702 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700703 oldPort.type() != newPort.type() ||
704 oldPort.portSpeed() != newPort.portSpeed() ||
705 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700706 ports.put(oldPort.number(), newPort);
707 return new DeviceEvent(PORT_UPDATED, device, newPort);
708 }
709 return null;
710 }
711
Michal Machce774332017-01-25 11:02:55 +0100712 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
713
714 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
715 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
716
717 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
718 }
719
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700720 // Prunes the specified list of ports based on which ports are in the
721 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700722 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700723 private List<DeviceEvent> pruneOldPorts(Device device,
724 Map<PortNumber, Port> ports,
725 Set<PortNumber> processed) {
726 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700727 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700728 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700729 Entry<PortNumber, Port> e = iterator.next();
730 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700731 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700732 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700733 iterator.remove();
734 }
735 }
736 return events;
737 }
738
739 // Gets the map of ports for the specified device; if one does not already
740 // exist, it creates and registers a new one.
741 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700742 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700743 }
744
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700745 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700746 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700747 Map<ProviderId, DeviceDescriptions> r;
748 r = deviceDescs.get(deviceId);
749 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700750 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700751 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
752 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
753 if (concurrentlyAdded != null) {
754 r = concurrentlyAdded;
755 }
756 }
757 return r;
758 }
759
760 // Guarded by deviceDescs value (=Device lock)
761 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
762 Map<ProviderId, DeviceDescriptions> device,
763 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700764 synchronized (device) {
765 DeviceDescriptions r = device.get(providerId);
766 if (r == null) {
767 r = new DeviceDescriptions(deltaDesc);
768 device.put(providerId, r);
769 }
770 return r;
771 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700772 }
773
774 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700775 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
776 DeviceId deviceId,
777 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700778 final Timestamp newTimestamp;
779 try {
780 newTimestamp = deviceClockService.getTimestamp(deviceId);
781 } catch (IllegalStateException e) {
782 log.info("Timestamp was not available for device {}", deviceId);
783 log.debug(" discarding {}", portDescription);
784 // Failed to generate timestamp. Ignoring.
785 // See updatePorts comment
786 return null;
787 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700788 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700789 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700790 final DeviceEvent event;
791 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800792 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
793 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700794 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800795 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700796 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700797 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700798 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700799 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700800 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800801 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700802 }
803 return event;
804 }
805
806 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700807 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700808 Device device = devices.get(deviceId);
809 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
810
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700811 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700812 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
813
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700814 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700815
816 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
817 log.debug("Ignoring outdated event: {}", deltaDesc);
818 return null;
819 }
820
821 DeviceDescriptions descs = descsMap.get(providerId);
822 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700823 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700824 "Device description for Device ID %s from Provider %s was not found",
825 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700826
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700827 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
828 final PortNumber number = deltaDesc.value().portNumber();
829 final Port oldPort = ports.get(number);
830 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700831 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100832 boolean toDelete = false;
833
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700834 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700835 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700836 // on new port or valid update
837 // update description
838 descs.putPortDesc(deltaDesc);
839 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100840 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700841 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700842 // same or outdated event, ignored.
843 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700844 return null;
845 }
846
847 if (oldPort == null) {
848 return createPort(device, newPort, ports);
849 } else {
Michal Machce774332017-01-25 11:02:55 +0100850 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700851 }
852 }
853 }
854
855 @Override
856 public List<Port> getPorts(DeviceId deviceId) {
857 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
858 if (ports == null) {
859 return Collections.emptyList();
860 }
861 return ImmutableList.copyOf(ports.values());
862 }
863
864 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700865 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
866 DeviceId deviceId) {
867 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
868 if (descs == null) {
Donghyeok Ho6de4fb92018-01-31 11:04:19 +0900869 return Stream.empty();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700870 }
871 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
872 final Optional<DeviceDescriptions> devDescs;
873 synchronized (descs) {
874 devDescs = Optional.ofNullable(descs.get(pid));
875 }
876 // DeviceDescriptions is concurrent access-safe
877 return devDescs
878 .map(dd -> dd.getPortDescs().values().stream()
879 .map(Timestamped::value))
880 .orElse(Stream.empty());
881 }
882
883 @Override
sangho538108b2015-04-08 14:29:20 -0700884 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200885 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700886
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200887 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
888 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
889 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
890
891 if (prvStatsMap != null) {
892 for (PortStatistics newStats : newStatsCollection) {
893 PortNumber port = PortNumber.portNumber(newStats.port());
894 PortStatistics prvStats = prvStatsMap.get(port);
895 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
896 PortStatistics deltaStats = builder.build();
897 if (prvStats != null) {
898 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
899 }
900 deltaStatsMap.put(port, deltaStats);
901 newStatsMap.put(port, newStats);
902 }
903 } else {
904 for (PortStatistics newStats : newStatsCollection) {
905 PortNumber port = PortNumber.portNumber(newStats.port());
906 newStatsMap.put(port, newStats);
907 }
sangho538108b2015-04-08 14:29:20 -0700908 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200909 devicePortDeltaStats.put(deviceId, deltaStatsMap);
910 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200911 // DeviceEvent returns null because of InternalPortStatsListener usage
912 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200913 }
914
915 /**
916 * Calculate delta statistics by subtracting previous from new statistics.
917 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700918 * @param deviceId device identifier
919 * @param prvStats previous port statistics
920 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200921 * @return PortStatistics
922 */
923 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
924 // calculate time difference
925 long deltaStatsSec, deltaStatsNano;
926 if (newStats.durationNano() < prvStats.durationNano()) {
927 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
928 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
929 } else {
930 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
931 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
932 }
933 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
934 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
935 .setPort(newStats.port())
936 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
937 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
938 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
939 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
940 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
941 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
942 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
943 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
944 .setDurationSec(deltaStatsSec)
945 .setDurationNano(deltaStatsNano)
946 .build();
947 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700948 }
949
950 @Override
951 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700952 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
953 if (portStats == null) {
954 return Collections.emptyList();
955 }
956 return ImmutableList.copyOf(portStats.values());
957 }
958
959 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530960 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
961 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
962 if (portStatsMap == null) {
963 return null;
964 }
965 PortStatistics portStats = portStatsMap.get(portNumber);
966 return portStats;
967 }
968
969 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200970 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
971 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
972 if (portStats == null) {
973 return Collections.emptyList();
974 }
975 return ImmutableList.copyOf(portStats.values());
976 }
977
978 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530979 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
980 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
981 if (portStatsMap == null) {
982 return null;
983 }
984 PortStatistics portStats = portStatsMap.get(portNumber);
985 return portStats;
986 }
987
988 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700989 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
990 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
991 return ports == null ? null : ports.get(portNumber);
992 }
993
994 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700995 public PortDescription getPortDescription(ProviderId pid,
996 DeviceId deviceId,
997 PortNumber portNumber) {
998 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
999 if (descs == null) {
1000 return null;
1001 }
1002 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1003 final Optional<DeviceDescriptions> devDescs;
1004 synchronized (descs) {
1005 devDescs = Optional.ofNullable(descs.get(pid));
1006 }
1007 // DeviceDescriptions is concurrent access-safe
1008 return devDescs
1009 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1010 .map(Timestamped::value)
1011 .orElse(null);
1012 }
1013
1014 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001015 public boolean isAvailable(DeviceId deviceId) {
1016 return availableDevices.contains(deviceId);
1017 }
1018
1019 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001020 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001021 final NodeId myId = clusterService.getLocalNode().id();
1022 NodeId master = mastershipService.getMasterFor(deviceId);
1023
1024 // if there exist a master, forward
1025 // if there is no master, try to become one and process
1026
1027 boolean relinquishAtEnd = false;
1028 if (master == null) {
1029 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1030 if (myRole != MastershipRole.NONE) {
1031 relinquishAtEnd = true;
1032 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001033 log.debug("Temporarily requesting role for {} to remove", deviceId);
Jordan Haltermanf1c602d2017-10-18 11:26:52 -07001034 if (mastershipService.requestRoleFor(deviceId).join() == MastershipRole.MASTER) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001035 master = myId;
1036 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001037 }
1038
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001039 boolean isMaster = myId.equals(master);
1040
1041 // If this node is not the master, forward the request.
1042 if (!isMaster) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001043 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001044 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001045
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001046 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001047 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001048 /* error log:
1049 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1050 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001051 }
1052
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001053 // If this node is the master, get a timestamp. Otherwise, default to the current device timestamp.
1054 Timestamp timestamp = isMaster ? deviceClockService.getTimestamp(deviceId) : null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001055
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001056 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001057
1058 // If this node is the master, update peers.
1059 if (isMaster && event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001060 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001061 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001062 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001063 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001064
1065 // Relinquish mastership if acquired to remove the device.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001066 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001067 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001068 mastershipService.relinquishMastership(deviceId);
1069 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001070 return event;
1071 }
1072
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001073 private DeviceEvent removeDeviceInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001074
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001075 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001076 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001077 // accept removal request if given timestamp is newer than
1078 // the latest Timestamp from Primary provider
1079 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001080 if (primDescs == null) {
1081 return null;
1082 }
1083
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001084 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001085
1086 // If no timestamp is set, default the timestamp to the last timestamp for the device.
1087 if (timestamp == null) {
1088 timestamp = lastTimestamp;
1089 }
1090
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001091 if (timestamp.compareTo(lastTimestamp) <= 0) {
1092 // outdated event ignore
1093 return null;
1094 }
1095 removalRequest.put(deviceId, timestamp);
1096
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001097 Device device = devices.remove(deviceId);
1098 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001099 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1100 if (ports != null) {
1101 ports.clear();
1102 }
1103 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001104 descs.clear();
1105 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001106 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001107 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001108 }
1109
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001110 /**
1111 * Checks if given timestamp is superseded by removal request
1112 * with more recent timestamp.
1113 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001114 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001115 * @param timestampToCheck timestamp of an event to check
1116 * @return true if device is already removed
1117 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001118 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1119 Timestamp removalTimestamp = removalRequest.get(deviceId);
1120 if (removalTimestamp != null &&
Jordan Halterman8a0b3972017-08-15 16:14:18 -07001121 removalTimestamp.compareTo(timestampToCheck) > 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001122 // removalRequest is more recent
1123 return true;
1124 }
1125 return false;
1126 }
1127
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001128 /**
1129 * Returns a Device, merging description given from multiple Providers.
1130 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001131 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001132 * @param providerDescs Collection of Descriptions from multiple providers
1133 * @return Device instance
1134 */
1135 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001136 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001137
Thomas Vachuska444eda62014-10-28 13:09:42 -07001138 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001139
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001140 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001141
1142 DeviceDescriptions desc = providerDescs.get(primary);
1143
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001144 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001145 Type type = base.type();
1146 String manufacturer = base.manufacturer();
1147 String hwVersion = base.hwVersion();
1148 String swVersion = base.swVersion();
1149 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001150 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001151 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1152 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001153
1154 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1155 if (e.getKey().equals(primary)) {
1156 continue;
1157 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001158 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001159 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001160 // Currently assuming there will never be a key conflict between
1161 // providers
1162
1163 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001164 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001165 }
1166
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001167 return new DefaultDevice(primary, deviceId, type, manufacturer,
1168 hwVersion, swVersion, serialNumber,
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001169 chassisId, annotations.buildCompressed());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001170 }
1171
Marc De Leenheer88194c32015-05-29 22:10:59 -07001172 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1173 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001174 return new DefaultPort(device, number, isEnabled, description.type(),
1175 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001176 }
1177
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001178 /**
1179 * Returns a Port, merging description given from multiple Providers.
1180 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001181 * @param device device the port is on
1182 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001183 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001184 * @return Port instance
1185 */
1186 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001187 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001188
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001189 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001190 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001191 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001192 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001193 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001194 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001195 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1196 if (portDesc != null) {
1197 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001198 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001199 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001200 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001201 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001202 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001203 if (e.getKey().equals(primary)) {
1204 continue;
1205 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001206 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001207 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001208 // Currently assuming there will never be a key conflict between
1209 // providers
1210
1211 // annotation merging. not so efficient, should revisit later
1212 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1213 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001214 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1215 continue;
1216 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001217 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001218 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001219 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001220 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001221 }
1222 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001223 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001224 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001225 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001226 PortDescription current = portDesc.value();
1227 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001228 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001229 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001230 }
1231
1232 /**
1233 * @return primary ProviderID, or randomly chosen one if none exists
1234 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001235 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001236 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001237 ProviderId fallBackPrimary = null;
1238 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1239 if (!e.getKey().isAncillary()) {
1240 return e.getKey();
1241 } else if (fallBackPrimary == null) {
1242 // pick randomly as a fallback in case there is no primary
1243 fallBackPrimary = e.getKey();
1244 }
1245 }
1246 return fallBackPrimary;
1247 }
1248
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001249 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001250 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001251 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001252 return providerDescs.get(pid);
1253 }
1254
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001255 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001256 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001257 }
1258
Jonathan Hart7d656f42015-01-27 14:07:23 -08001259 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001260 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001261 }
Madan Jampani47c93732014-10-06 20:46:08 -07001262
Jonathan Hart7d656f42015-01-27 14:07:23 -08001263 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001264 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001265 }
1266
Palash Kala6c526062018-04-03 18:25:11 +09001267 private void notifyPeers(InternalDeviceStatusChangeEvent event) {
1268 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001269 }
1270
Jonathan Hart7d656f42015-01-27 14:07:23 -08001271 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001272 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001273 }
1274
Jonathan Hart7d656f42015-01-27 14:07:23 -08001275 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001276 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001277 }
1278
Jonathan Hart7d656f42015-01-27 14:07:23 -08001279 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001280 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1281 }
1282
1283 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1284 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001285 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001286 } catch (IOException e) {
1287 log.error("Failed to send" + event + " to " + recipient, e);
1288 }
1289 }
1290
Palash Kala6c526062018-04-03 18:25:11 +09001291 private void notifyPeer(NodeId recipient, InternalDeviceStatusChangeEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001292 try {
Palash Kala6c526062018-04-03 18:25:11 +09001293 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001294 } catch (IOException e) {
1295 log.error("Failed to send" + event + " to " + recipient, e);
1296 }
1297 }
1298
1299 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1300 try {
1301 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1302 } catch (IOException e) {
1303 log.error("Failed to send" + event + " to " + recipient, e);
1304 }
1305 }
1306
1307 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1308 try {
1309 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1310 } catch (IOException e) {
1311 log.error("Failed to send" + event + " to " + recipient, e);
1312 }
1313 }
1314
1315 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1316 try {
1317 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1318 } catch (IOException e) {
1319 log.error("Failed to send" + event + " to " + recipient, e);
1320 }
1321 }
1322
1323 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1324 final NodeId self = clusterService.getLocalNode().id();
1325
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001326 final int numDevices = deviceDescs.size();
1327 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1328 final int portsPerDevice = 8; // random factor to minimize reallocation
1329 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1330 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001331
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001332 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001333
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001334 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001335 synchronized (devDescs) {
1336
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001337 // send device offline timestamp
1338 Timestamp lOffline = this.offline.get(deviceId);
1339 if (lOffline != null) {
1340 adOffline.put(deviceId, lOffline);
1341 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001342
1343 for (Entry<ProviderId, DeviceDescriptions>
1344 prov : devDescs.entrySet()) {
1345
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001346 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001347 final ProviderId provId = prov.getKey();
1348 final DeviceDescriptions descs = prov.getValue();
1349
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001350 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001351 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001352
1353 for (Entry<PortNumber, Timestamped<PortDescription>>
1354 portDesc : descs.getPortDescs().entrySet()) {
1355
1356 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001357 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001358 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001359 }
1360 }
1361 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001362 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001363
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001364 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001365 }
1366
1367 /**
1368 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001369 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001370 * Notify sender about out-dated information using regular replication message.
1371 * Send back advertisement to sender if not in sync.
1372 *
1373 * @param advertisement to respond to
1374 */
1375 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1376
1377 final NodeId sender = advertisement.sender();
1378
1379 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1380 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1381 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1382
1383 // Fragments to request
1384 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1385 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1386
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001387 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001388 final DeviceId deviceId = de.getKey();
1389 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1390
1391 synchronized (lDevice) {
1392 // latestTimestamp across provider
1393 // Note: can be null initially
1394 Timestamp localLatest = offline.get(deviceId);
1395
1396 // handle device Ads
1397 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1398 final ProviderId provId = prov.getKey();
1399 final DeviceDescriptions lDeviceDescs = prov.getValue();
1400
1401 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1402
1403
1404 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1405 Timestamp advDevTimestamp = devAds.get(devFragId);
1406
Jonathan Hart403ea932015-02-20 16:23:00 -08001407 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1408 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001409 // remote does not have it or outdated, suggest
1410 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1411 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1412 // local is outdated, request
1413 reqDevices.add(devFragId);
1414 }
1415
1416 // handle port Ads
1417 for (Entry<PortNumber, Timestamped<PortDescription>>
1418 pe : lDeviceDescs.getPortDescs().entrySet()) {
1419
1420 final PortNumber num = pe.getKey();
1421 final Timestamped<PortDescription> lPort = pe.getValue();
1422
1423 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1424
1425 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001426 if (advPortTimestamp == null || lPort.isNewerThan(
1427 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001428 // remote does not have it or outdated, suggest
1429 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1430 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1431 // local is outdated, request
1432 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1433 reqPorts.add(portFragId);
1434 }
1435
1436 // remove port Ad already processed
1437 portAds.remove(portFragId);
1438 } // end local port loop
1439
1440 // remove device Ad already processed
1441 devAds.remove(devFragId);
1442
1443 // find latest and update
1444 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1445 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001446 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001447 localLatest = providerLatest;
1448 }
1449 } // end local provider loop
1450
1451 // checking if remote timestamp is more recent.
1452 Timestamp rOffline = offlineAds.get(deviceId);
jaegonkim73c21bd2018-01-13 10:52:02 +09001453 if (localLatest == null || (rOffline != null && rOffline.compareTo(localLatest) > 0)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001454 // remote offline timestamp suggests that the
1455 // device is off-line
1456 markOfflineInternal(deviceId, rOffline);
1457 }
1458
1459 Timestamp lOffline = offline.get(deviceId);
1460 if (lOffline != null && rOffline == null) {
1461 // locally offline, but remote is online, suggest offline
Palash Kala6c526062018-04-03 18:25:11 +09001462 notifyPeer(sender, new InternalDeviceStatusChangeEvent(deviceId, lOffline, false));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001463 }
1464
1465 // remove device offline Ad already processed
1466 offlineAds.remove(deviceId);
1467 } // end local device loop
1468 } // device lock
1469
1470 // If there is any Ads left, request them
1471 log.trace("Ads left {}, {}", devAds, portAds);
1472 reqDevices.addAll(devAds.keySet());
1473 reqPorts.addAll(portAds.keySet());
1474
1475 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1476 log.trace("Nothing to request to remote peer {}", sender);
1477 return;
1478 }
1479
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001480 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001481
1482 // 2-way Anti-Entropy for now
1483 try {
1484 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1485 } catch (IOException e) {
1486 log.error("Failed to send response advertisement to " + sender, e);
1487 }
1488
1489// Sketch of 3-way Anti-Entropy
1490// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1491// ClusterMessage message = new ClusterMessage(
1492// clusterService.getLocalNode().id(),
1493// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1494// SERIALIZER.encode(request));
1495//
1496// try {
1497// clusterCommunicator.unicast(message, advertisement.sender());
1498// } catch (IOException e) {
1499// log.error("Failed to send advertisement reply to "
1500// + advertisement.sender(), e);
1501// }
Madan Jampani47c93732014-10-06 20:46:08 -07001502 }
1503
Madan Jampani255a58b2014-10-09 12:08:20 -07001504 private void notifyDelegateIfNotNull(DeviceEvent event) {
1505 if (event != null) {
1506 notifyDelegate(event);
1507 }
1508 }
1509
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001510 private final class SendAdvertisementTask implements Runnable {
1511
1512 @Override
1513 public void run() {
1514 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001515 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001516 return;
1517 }
1518
1519 try {
1520 final NodeId self = clusterService.getLocalNode().id();
1521 Set<ControllerNode> nodes = clusterService.getNodes();
1522
1523 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1524 .transform(toNodeId())
1525 .toList();
1526
1527 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001528 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001529 return;
1530 }
1531
1532 NodeId peer;
1533 do {
1534 int idx = RandomUtils.nextInt(0, nodeIds.size());
1535 peer = nodeIds.get(idx);
1536 } while (peer.equals(self));
1537
1538 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1539
1540 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001541 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001542 return;
1543 }
1544
1545 try {
1546 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1547 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001548 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001549 return;
1550 }
1551 } catch (Exception e) {
1552 // catch all Exception to avoid Scheduled task being suppressed.
1553 log.error("Exception thrown while sending advertisement", e);
1554 }
1555 }
1556 }
1557
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001558 private void handleDeviceEvent(InternalDeviceEvent event) {
1559 ProviderId providerId = event.providerId();
1560 DeviceId deviceId = event.deviceId();
1561 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001562
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001563 try {
1564 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1565 deviceDescription));
1566 } catch (Exception e) {
1567 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001568 }
1569 }
1570
Palash Kala6c526062018-04-03 18:25:11 +09001571 private void handleDeviceStatusChangeEvent(InternalDeviceStatusChangeEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001572 DeviceId deviceId = event.deviceId();
1573 Timestamp timestamp = event.timestamp();
Palash Kala6c526062018-04-03 18:25:11 +09001574 Boolean available = event.available();
Madan Jampani25322532014-10-08 11:20:38 -07001575
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001576 try {
Palash Kala6c526062018-04-03 18:25:11 +09001577 if (available) {
1578 notifyDelegateIfNotNull(markOnlineInternal(deviceId, timestamp));
1579 } else {
1580 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1581 }
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001582 } catch (Exception e) {
Palash Kala6c526062018-04-03 18:25:11 +09001583 log.warn("Exception thrown handling device status change event", e);
Madan Jampani25322532014-10-08 11:20:38 -07001584 }
1585 }
1586
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001587 private void handleRemoveRequest(DeviceId did) {
1588 try {
Jayasree Ghosh7d96d6a2017-02-27 18:35:32 +05301589 DeviceEvent event = removeDevice(did);
1590 notifyDelegateIfNotNull(event);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001591 } catch (Exception e) {
1592 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001593 }
1594 }
1595
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001596 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1597 DeviceId deviceId = event.deviceId();
1598 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001599
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001600 try {
1601 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1602 } catch (Exception e) {
1603 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001604 }
1605 }
1606
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001607 private void handlePortEvent(InternalPortEvent event) {
1608 ProviderId providerId = event.providerId();
1609 DeviceId deviceId = event.deviceId();
1610 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001611
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001612 if (getDevice(deviceId) == null) {
1613 log.debug("{} not found on this node yet, ignoring.", deviceId);
1614 // Note: dropped information will be recovered by anti-entropy
1615 return;
1616 }
Madan Jampani47c93732014-10-06 20:46:08 -07001617
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001618 try {
1619 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1620 } catch (Exception e) {
1621 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001622 }
1623 }
1624
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001625 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1626 ProviderId providerId = event.providerId();
1627 DeviceId deviceId = event.deviceId();
1628 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001629
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001630 if (getDevice(deviceId) == null) {
1631 log.debug("{} not found on this node yet, ignoring.", deviceId);
1632 // Note: dropped information will be recovered by anti-entropy
1633 return;
1634 }
Madan Jampani47c93732014-10-06 20:46:08 -07001635
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001636 try {
1637 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1638 } catch (Exception e) {
1639 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001640 }
1641 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001642
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001643 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1644 try {
1645 handleAdvertisement(advertisement);
1646 } catch (Exception e) {
1647 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001648 }
1649 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001650
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001651 private class InternalPortStatsListener
1652 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1653 @Override
1654 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1655 if (event.type() == PUT) {
1656 Device device = devices.get(event.key());
1657 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001658 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001659 }
1660 }
1661 }
1662 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001663}