blob: e95d00da8cebbdf0e061efae47083d4ba673a95a [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));
Andrea Campanellabba1e882018-05-14 18:17:28 +0200331 notifyDelegateIfNotNull(deviceEvent);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800332
333 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700334 }
335
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700336 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700337 DeviceId deviceId,
338 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700339
340 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800341 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700342 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700343
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800344 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700345 // locking per device
346
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700347 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
348 log.debug("Ignoring outdated event: {}", deltaDesc);
349 return null;
350 }
351
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800352 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700353
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700354 final Device oldDevice = devices.get(deviceId);
355 final Device newDevice;
356
357 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700358 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700359 // on new device or valid update
360 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800361 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700362 } else {
363 // outdated event, ignored.
364 return null;
365 }
Thomas Vachuskaf131e592018-05-07 11:52:14 -0700366
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700367 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700368 // REGISTER
369 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700370 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700371 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700372 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700373 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700374 } else {
375 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700376 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
377 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700378 }
379 }
380 }
381
382 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700383 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700384 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700385 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700386
387 // update composed device cache
388 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
389 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700390 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
391 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700392
393 if (!providerId.isAncillary()) {
Palash Kala6c526062018-04-03 18:25:11 +0900394 markOnline(newDevice.id(), timestamp, false);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700395 }
396
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700397 log.debug("Device {} added", newDevice.id());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700398 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
399 }
400
401 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700402 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700403 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700404 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700405 Device newDevice, Timestamp newTimestamp,
406 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700407 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700408 boolean propertiesChanged =
409 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700410 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
mskala4b2081a2017-06-12 16:39:50 +0200411 !Objects.equals(oldDevice.providerId(), newDevice.providerId()) ||
412 !Objects.equals(oldDevice.chassisId(), newDevice.chassisId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700413 boolean annotationsChanged =
414 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700415
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700416 // Primary providers can respond to all changes, but ancillary ones
417 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800418 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700419 if ((providerId.isAncillary() && annotationsChanged) ||
420 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700421 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
422 if (!replaced) {
423 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700424 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800425 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700426 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700427
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700428 log.debug("Device {} updated", newDevice.id());
alshabibdc5d8bd2015-11-02 15:41:29 -0800429 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700430 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800431
helenyrwufd296b62016-06-22 17:43:02 -0700432 if (!providerId.isAncillary() && forceAvailable) {
Palash Kala6c526062018-04-03 18:25:11 +0900433 notifyDelegateIfNotNull(markOnline(newDevice.id(), newTimestamp, false));
alshabibdc5d8bd2015-11-02 15:41:29 -0800434 }
435 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700436 }
437
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700438 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700439 // update composed device cache
440 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
441 verify(oldDevice == null,
442 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
443 providerId, oldDevice, newDevice);
444
445 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700446 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700447 }
448
449 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
450 }
451
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700452 @Override
453 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700454 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
455 }
456
457 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700458 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700459 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700460 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700461 deviceId, timestamp);
Palash Kala6c526062018-04-03 18:25:11 +0900462 notifyPeers(new InternalDeviceStatusChangeEvent(deviceId, timestamp, false));
Madan Jampani25322532014-10-08 11:20:38 -0700463 }
464 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700465 }
466
467 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700468 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700469 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700470
471 // locking device
472 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700473 // accept off-line if given timestamp is newer than
474 // the latest Timestamp from Primary provider
475 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
jaegonkim73c21bd2018-01-13 10:52:02 +0900476 if (primDescs != null) {
477 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
478 if (lastTimestamp == null) {
479 lastTimestamp = deviceClockService.getTimestamp(deviceId);
480 }
481 if (timestamp.compareTo(lastTimestamp) <= 0) {
482 // outdated event ignore
483 return null;
484 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700485 }
486
487 offline.put(deviceId, timestamp);
488
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700489 Device device = devices.get(deviceId);
490 if (device == null) {
Andrea Campanellabba1e882018-05-14 18:17:28 +0200491 // Single Instance ONOS, device is removed from devices map and is null here but
492 // must still be marked offline
493 availableDevices.remove(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700494 return null;
495 }
496 boolean removed = availableDevices.remove(deviceId);
497 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700498 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700499 }
500 return null;
501 }
502 }
503
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700504 @Override
Palash Kala6c526062018-04-03 18:25:11 +0900505 public DeviceEvent markOnline(DeviceId deviceId) {
506 return markOnline(deviceId, deviceClockService.getTimestamp(deviceId), true);
helenyrwufd296b62016-06-22 17:43:02 -0700507 }
508
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700509 /**
510 * Marks the device as available if the given timestamp is not outdated,
511 * compared to the time the device has been marked offline.
512 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700513 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700514 * @param timestamp of the event triggering this change.
Palash Kala6c526062018-04-03 18:25:11 +0900515 * @param notifyPeers if the event needs to be notified to peers.
516 * @return ready to send event describing what occurred; null if no change
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700517 */
Palash Kala6c526062018-04-03 18:25:11 +0900518 private DeviceEvent markOnline(DeviceId deviceId, Timestamp timestamp, boolean notifyPeers) {
519 final DeviceEvent event = markOnlineInternal(deviceId, timestamp);
520 if (event != null && notifyPeers) {
521 log.debug("Notifying peers of a device online topology event for deviceId: {} {}",
522 deviceId, timestamp);
523 notifyPeers(new InternalDeviceStatusChangeEvent(deviceId, timestamp, true));
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700524 }
Palash Kala6c526062018-04-03 18:25:11 +0900525 return event;
526 }
527
528 // Guarded by deviceDescs value (=Device lock)
529 private DeviceEvent markOnlineInternal(DeviceId deviceId, Timestamp timestamp) {
530 if (devices.containsKey(deviceId)) {
531 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
532 synchronized (deviceLock) {
533 // accept on-line if given timestamp is newer than
534 // the latest offline request Timestamp
535 Timestamp offlineTimestamp = offline.get(deviceId);
536 if (offlineTimestamp == null ||
537 offlineTimestamp.compareTo(timestamp) < 0) {
538 offline.remove(deviceId);
539 Device device = devices.get(deviceId);
540 boolean add = availableDevices.add(deviceId);
541 if (add) {
542 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
543 }
544 }
545 }
Thomas Vachuskae36a2822018-05-03 12:16:52 -0700546 } else {
547 log.warn("Device {} does not exist in store", deviceId);
Palash Kala6c526062018-04-03 18:25:11 +0900548 }
Palash Kala6c526062018-04-03 18:25:11 +0900549 return null;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700550 }
551
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700552 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700553 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700554 DeviceId deviceId,
555 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700556
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800557 NodeId localNode = clusterService.getLocalNode().id();
558 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
559 // since it will trigger distributed store read.
560 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
561 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
562 // If we don't care much about topology performance, then it might be OK.
563 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700564
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800565 // Process port update only if we're the master of the device,
566 // otherwise signal the actual master.
567 List<DeviceEvent> deviceEvents = null;
568 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700569
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800570 final Timestamp newTimestamp;
571 try {
572 newTimestamp = deviceClockService.getTimestamp(deviceId);
573 } catch (IllegalStateException e) {
574 log.info("Timestamp was not available for device {}", deviceId);
575 log.debug(" discarding {}", portDescriptions);
576 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700577
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800578 // Possible situation:
579 // Device connected and became master for short period of time,
580 // but lost mastership before this instance had the chance to
581 // retrieve term information.
582
583 // Information dropped here is expected to be recoverable by
584 // device probing after mastership change
585
586 return Collections.emptyList();
587 }
588 log.debug("timestamp for {} {}", deviceId, newTimestamp);
589
590 final Timestamped<List<PortDescription>> timestampedInput
591 = new Timestamped<>(portDescriptions, newTimestamp);
592 final Timestamped<List<PortDescription>> merged;
593
594 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
595
596 synchronized (device) {
597 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
598 final DeviceDescriptions descs = device.get(providerId);
599 List<PortDescription> mergedList =
600 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700601 .transform(input ->
602 // lookup merged port description
603 descs.getPortDesc(input.portNumber()).value()
604 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700605 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800606 }
607
608 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700609 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700610 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800611 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
612 }
613
614 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700615 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700616 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700617
Ray Milkeyfe0e0852018-01-18 11:14:05 -0800618 return deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700619 }
620
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700621 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700622 DeviceId deviceId,
623 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700624
625 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700626 if (device == null) {
627 log.debug("Device is no longer valid: {}", deviceId);
628 return Collections.emptyList();
629 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700630
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700631 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700632 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
633
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700634 List<DeviceEvent> events = new ArrayList<>();
635 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700636
637 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
638 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700639 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700640 }
641
642 DeviceDescriptions descs = descsMap.get(providerId);
643 // every provider must provide DeviceDescription.
644 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700645 "Device description for Device ID %s from Provider %s was not found",
646 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700647
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700648 Map<PortNumber, Port> ports = getPortMap(deviceId);
649
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700650 final Timestamp newTimestamp = portDescriptions.timestamp();
651
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700652 // Add new ports
653 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700654 for (PortDescription portDescription : portDescriptions.value()) {
655 final PortNumber number = portDescription.portNumber();
656 processed.add(number);
657
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700658 final Port oldPort = ports.get(number);
659 final Port newPort;
Palash Kala8d30b612018-03-02 11:06:10 +0900660 boolean isRemoved = portDescription.isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700661
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700662
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700663 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
664 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700665 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700666 // on new port or valid update
667 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700668 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700669 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700670 newPort = composePort(device, number, descsMap);
671 } else {
672 // outdated event, ignored.
673 continue;
674 }
675
Palash Kala8d30b612018-03-02 11:06:10 +0900676 if (isRemoved && oldPort != null) {
677 events.add(removePort(deviceId, oldPort.number()));
678 } else if (!isRemoved) {
679 events.add(oldPort == null ?
680 createPort(device, newPort, ports) :
681 updatePort(device, oldPort, newPort, ports));
682 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700683 }
684
685 events.addAll(pruneOldPorts(device, ports, processed));
686 }
687 return FluentIterable.from(events).filter(notNull()).toList();
688 }
689
690 // Creates a new port based on the port description adds it to the map and
691 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700692 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700693 private DeviceEvent createPort(Device device, Port newPort,
694 Map<PortNumber, Port> ports) {
695 ports.put(newPort.number(), newPort);
696 return new DeviceEvent(PORT_ADDED, device, newPort);
697 }
698
699 // Checks if the specified port requires update and if so, it replaces the
700 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700701 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700702 private DeviceEvent updatePort(Device device, Port oldPort,
703 Port newPort,
704 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100705
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700706 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700707 oldPort.type() != newPort.type() ||
708 oldPort.portSpeed() != newPort.portSpeed() ||
709 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700710 ports.put(oldPort.number(), newPort);
711 return new DeviceEvent(PORT_UPDATED, device, newPort);
712 }
713 return null;
714 }
715
Michal Machce774332017-01-25 11:02:55 +0100716 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
717
718 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
719 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
720
721 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
722 }
723
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700724 // Prunes the specified list of ports based on which ports are in the
725 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700726 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700727 private List<DeviceEvent> pruneOldPorts(Device device,
728 Map<PortNumber, Port> ports,
729 Set<PortNumber> processed) {
730 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700731 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700732 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700733 Entry<PortNumber, Port> e = iterator.next();
734 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700735 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700736 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700737 iterator.remove();
738 }
739 }
740 return events;
741 }
742
743 // Gets the map of ports for the specified device; if one does not already
744 // exist, it creates and registers a new one.
745 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700746 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700747 }
748
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700749 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700750 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700751 Map<ProviderId, DeviceDescriptions> r;
752 r = deviceDescs.get(deviceId);
753 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700754 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700755 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
756 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
757 if (concurrentlyAdded != null) {
758 r = concurrentlyAdded;
759 }
760 }
761 return r;
762 }
763
764 // Guarded by deviceDescs value (=Device lock)
765 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
766 Map<ProviderId, DeviceDescriptions> device,
767 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700768 synchronized (device) {
769 DeviceDescriptions r = device.get(providerId);
770 if (r == null) {
771 r = new DeviceDescriptions(deltaDesc);
772 device.put(providerId, r);
773 }
774 return r;
775 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700776 }
777
778 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700779 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
780 DeviceId deviceId,
781 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700782 final Timestamp newTimestamp;
783 try {
784 newTimestamp = deviceClockService.getTimestamp(deviceId);
785 } catch (IllegalStateException e) {
786 log.info("Timestamp was not available for device {}", deviceId);
787 log.debug(" discarding {}", portDescription);
788 // Failed to generate timestamp. Ignoring.
789 // See updatePorts comment
790 return null;
791 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700792 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700793 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700794 final DeviceEvent event;
795 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800796 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
797 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700798 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800799 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700800 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700801 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700802 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700803 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700804 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800805 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700806 }
807 return event;
808 }
809
810 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700811 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700812 Device device = devices.get(deviceId);
813 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
814
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700815 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700816 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
817
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700818 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700819
820 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
821 log.debug("Ignoring outdated event: {}", deltaDesc);
822 return null;
823 }
824
825 DeviceDescriptions descs = descsMap.get(providerId);
826 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700827 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700828 "Device description for Device ID %s from Provider %s was not found",
829 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700830
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700831 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
832 final PortNumber number = deltaDesc.value().portNumber();
833 final Port oldPort = ports.get(number);
834 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700835 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100836 boolean toDelete = false;
837
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700838 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700839 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700840 // on new port or valid update
841 // update description
842 descs.putPortDesc(deltaDesc);
843 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100844 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700845 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700846 // same or outdated event, ignored.
847 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700848 return null;
849 }
850
851 if (oldPort == null) {
852 return createPort(device, newPort, ports);
853 } else {
Michal Machce774332017-01-25 11:02:55 +0100854 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700855 }
856 }
857 }
858
859 @Override
860 public List<Port> getPorts(DeviceId deviceId) {
861 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
862 if (ports == null) {
863 return Collections.emptyList();
864 }
865 return ImmutableList.copyOf(ports.values());
866 }
867
868 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700869 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
870 DeviceId deviceId) {
871 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
872 if (descs == null) {
Donghyeok Ho6de4fb92018-01-31 11:04:19 +0900873 return Stream.empty();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700874 }
875 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
876 final Optional<DeviceDescriptions> devDescs;
877 synchronized (descs) {
878 devDescs = Optional.ofNullable(descs.get(pid));
879 }
880 // DeviceDescriptions is concurrent access-safe
881 return devDescs
882 .map(dd -> dd.getPortDescs().values().stream()
883 .map(Timestamped::value))
884 .orElse(Stream.empty());
885 }
886
887 @Override
sangho538108b2015-04-08 14:29:20 -0700888 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200889 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700890
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200891 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
892 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
893 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
894
895 if (prvStatsMap != null) {
896 for (PortStatistics newStats : newStatsCollection) {
897 PortNumber port = PortNumber.portNumber(newStats.port());
898 PortStatistics prvStats = prvStatsMap.get(port);
899 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
900 PortStatistics deltaStats = builder.build();
901 if (prvStats != null) {
902 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
903 }
904 deltaStatsMap.put(port, deltaStats);
905 newStatsMap.put(port, newStats);
906 }
907 } else {
908 for (PortStatistics newStats : newStatsCollection) {
909 PortNumber port = PortNumber.portNumber(newStats.port());
910 newStatsMap.put(port, newStats);
911 }
sangho538108b2015-04-08 14:29:20 -0700912 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200913 devicePortDeltaStats.put(deviceId, deltaStatsMap);
914 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200915 // DeviceEvent returns null because of InternalPortStatsListener usage
916 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200917 }
918
919 /**
920 * Calculate delta statistics by subtracting previous from new statistics.
921 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700922 * @param deviceId device identifier
923 * @param prvStats previous port statistics
924 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200925 * @return PortStatistics
926 */
927 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
928 // calculate time difference
929 long deltaStatsSec, deltaStatsNano;
930 if (newStats.durationNano() < prvStats.durationNano()) {
931 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
932 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
933 } else {
934 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
935 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
936 }
937 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
938 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
939 .setPort(newStats.port())
940 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
941 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
942 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
943 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
944 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
945 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
946 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
947 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
948 .setDurationSec(deltaStatsSec)
949 .setDurationNano(deltaStatsNano)
950 .build();
951 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700952 }
953
954 @Override
955 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700956 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
957 if (portStats == null) {
958 return Collections.emptyList();
959 }
960 return ImmutableList.copyOf(portStats.values());
961 }
962
963 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530964 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
965 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
966 if (portStatsMap == null) {
967 return null;
968 }
969 PortStatistics portStats = portStatsMap.get(portNumber);
970 return portStats;
971 }
972
973 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200974 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
975 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
976 if (portStats == null) {
977 return Collections.emptyList();
978 }
979 return ImmutableList.copyOf(portStats.values());
980 }
981
982 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530983 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
984 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
985 if (portStatsMap == null) {
986 return null;
987 }
988 PortStatistics portStats = portStatsMap.get(portNumber);
989 return portStats;
990 }
991
992 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700993 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
994 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
995 return ports == null ? null : ports.get(portNumber);
996 }
997
998 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700999 public PortDescription getPortDescription(ProviderId pid,
1000 DeviceId deviceId,
1001 PortNumber portNumber) {
1002 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1003 if (descs == null) {
1004 return null;
1005 }
1006 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1007 final Optional<DeviceDescriptions> devDescs;
1008 synchronized (descs) {
1009 devDescs = Optional.ofNullable(descs.get(pid));
1010 }
1011 // DeviceDescriptions is concurrent access-safe
1012 return devDescs
1013 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1014 .map(Timestamped::value)
1015 .orElse(null);
1016 }
1017
1018 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001019 public boolean isAvailable(DeviceId deviceId) {
1020 return availableDevices.contains(deviceId);
1021 }
1022
1023 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001024 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001025 final NodeId myId = clusterService.getLocalNode().id();
1026 NodeId master = mastershipService.getMasterFor(deviceId);
1027
1028 // if there exist a master, forward
1029 // if there is no master, try to become one and process
1030
1031 boolean relinquishAtEnd = false;
1032 if (master == null) {
1033 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1034 if (myRole != MastershipRole.NONE) {
1035 relinquishAtEnd = true;
1036 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001037 log.debug("Temporarily requesting role for {} to remove", deviceId);
Jordan Haltermanf1c602d2017-10-18 11:26:52 -07001038 if (mastershipService.requestRoleFor(deviceId).join() == MastershipRole.MASTER) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001039 master = myId;
1040 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001041 }
1042
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001043 boolean isMaster = myId.equals(master);
1044
1045 // If this node is not the master, forward the request.
1046 if (!isMaster) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001047 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001048 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001049
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001050 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001051 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001052 /* error log:
1053 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1054 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001055 }
1056
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001057 // If this node is the master, get a timestamp. Otherwise, default to the current device timestamp.
1058 Timestamp timestamp = isMaster ? deviceClockService.getTimestamp(deviceId) : null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001059
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001060 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001061
1062 // If this node is the master, update peers.
1063 if (isMaster && event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001064 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001065 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001066 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Andrea Campanellabba1e882018-05-14 18:17:28 +02001067 notifyDelegateIfNotNull(event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001068 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001069
1070 // Relinquish mastership if acquired to remove the device.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001071 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001072 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001073 mastershipService.relinquishMastership(deviceId);
1074 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001075 return event;
1076 }
1077
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001078 private DeviceEvent removeDeviceInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001079
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001080 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001081 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001082 // accept removal request if given timestamp is newer than
1083 // the latest Timestamp from Primary provider
1084 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001085 if (primDescs == null) {
1086 return null;
1087 }
1088
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001089 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001090
1091 // If no timestamp is set, default the timestamp to the last timestamp for the device.
1092 if (timestamp == null) {
1093 timestamp = lastTimestamp;
1094 }
1095
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001096 if (timestamp.compareTo(lastTimestamp) <= 0) {
1097 // outdated event ignore
1098 return null;
1099 }
1100 removalRequest.put(deviceId, timestamp);
1101
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001102 Device device = devices.remove(deviceId);
1103 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001104 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1105 if (ports != null) {
1106 ports.clear();
1107 }
1108 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001109 descs.clear();
1110 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001111 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001112 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001113 }
1114
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001115 /**
1116 * Checks if given timestamp is superseded by removal request
1117 * with more recent timestamp.
1118 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001119 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001120 * @param timestampToCheck timestamp of an event to check
1121 * @return true if device is already removed
1122 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001123 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1124 Timestamp removalTimestamp = removalRequest.get(deviceId);
1125 if (removalTimestamp != null &&
Jordan Halterman8a0b3972017-08-15 16:14:18 -07001126 removalTimestamp.compareTo(timestampToCheck) > 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001127 // removalRequest is more recent
1128 return true;
1129 }
1130 return false;
1131 }
1132
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001133 /**
1134 * Returns a Device, merging description given from multiple Providers.
1135 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001136 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001137 * @param providerDescs Collection of Descriptions from multiple providers
1138 * @return Device instance
1139 */
1140 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001141 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001142
Thomas Vachuska444eda62014-10-28 13:09:42 -07001143 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001144
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001145 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001146
1147 DeviceDescriptions desc = providerDescs.get(primary);
1148
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001149 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001150 Type type = base.type();
1151 String manufacturer = base.manufacturer();
1152 String hwVersion = base.hwVersion();
1153 String swVersion = base.swVersion();
1154 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001155 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001156 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1157 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001158
1159 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1160 if (e.getKey().equals(primary)) {
1161 continue;
1162 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001163 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001164 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001165 // Currently assuming there will never be a key conflict between
1166 // providers
1167
1168 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001169 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001170 }
1171
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001172 return new DefaultDevice(primary, deviceId, type, manufacturer,
1173 hwVersion, swVersion, serialNumber,
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001174 chassisId, annotations.buildCompressed());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001175 }
1176
Marc De Leenheer88194c32015-05-29 22:10:59 -07001177 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1178 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001179 return new DefaultPort(device, number, isEnabled, description.type(),
1180 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001181 }
1182
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001183 /**
1184 * Returns a Port, merging description given from multiple Providers.
1185 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001186 * @param device device the port is on
1187 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001188 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001189 * @return Port instance
1190 */
1191 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001192 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001193
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001194 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001195 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001196 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001197 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001198 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001199 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001200 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1201 if (portDesc != null) {
1202 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001203 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001204 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001205 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001206 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001207 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001208 if (e.getKey().equals(primary)) {
1209 continue;
1210 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001211 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001212 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001213 // Currently assuming there will never be a key conflict between
1214 // providers
1215
1216 // annotation merging. not so efficient, should revisit later
1217 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1218 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001219 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1220 continue;
1221 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001222 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001223 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001224 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001225 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001226 }
1227 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001228 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001229 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001230 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001231 PortDescription current = portDesc.value();
1232 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001233 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001234 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001235 }
1236
1237 /**
1238 * @return primary ProviderID, or randomly chosen one if none exists
1239 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001240 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001241 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001242 ProviderId fallBackPrimary = null;
1243 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1244 if (!e.getKey().isAncillary()) {
1245 return e.getKey();
1246 } else if (fallBackPrimary == null) {
1247 // pick randomly as a fallback in case there is no primary
1248 fallBackPrimary = e.getKey();
1249 }
1250 }
1251 return fallBackPrimary;
1252 }
1253
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001254 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001255 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001256 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001257 return providerDescs.get(pid);
1258 }
1259
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001260 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001261 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001262 }
1263
Jonathan Hart7d656f42015-01-27 14:07:23 -08001264 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001265 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001266 }
Madan Jampani47c93732014-10-06 20:46:08 -07001267
Jonathan Hart7d656f42015-01-27 14:07:23 -08001268 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001269 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001270 }
1271
Palash Kala6c526062018-04-03 18:25:11 +09001272 private void notifyPeers(InternalDeviceStatusChangeEvent event) {
1273 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001274 }
1275
Jonathan Hart7d656f42015-01-27 14:07:23 -08001276 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001277 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001278 }
1279
Jonathan Hart7d656f42015-01-27 14:07:23 -08001280 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001281 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001282 }
1283
Jonathan Hart7d656f42015-01-27 14:07:23 -08001284 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001285 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1286 }
1287
1288 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1289 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001290 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001291 } catch (IOException e) {
1292 log.error("Failed to send" + event + " to " + recipient, e);
1293 }
1294 }
1295
Palash Kala6c526062018-04-03 18:25:11 +09001296 private void notifyPeer(NodeId recipient, InternalDeviceStatusChangeEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001297 try {
Palash Kala6c526062018-04-03 18:25:11 +09001298 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001299 } catch (IOException e) {
1300 log.error("Failed to send" + event + " to " + recipient, e);
1301 }
1302 }
1303
1304 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1305 try {
1306 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1307 } catch (IOException e) {
1308 log.error("Failed to send" + event + " to " + recipient, e);
1309 }
1310 }
1311
1312 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1313 try {
1314 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1315 } catch (IOException e) {
1316 log.error("Failed to send" + event + " to " + recipient, e);
1317 }
1318 }
1319
1320 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1321 try {
1322 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1323 } catch (IOException e) {
1324 log.error("Failed to send" + event + " to " + recipient, e);
1325 }
1326 }
1327
1328 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1329 final NodeId self = clusterService.getLocalNode().id();
1330
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001331 final int numDevices = deviceDescs.size();
1332 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1333 final int portsPerDevice = 8; // random factor to minimize reallocation
1334 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1335 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001336
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001337 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001338
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001339 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001340 synchronized (devDescs) {
1341
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001342 // send device offline timestamp
1343 Timestamp lOffline = this.offline.get(deviceId);
1344 if (lOffline != null) {
1345 adOffline.put(deviceId, lOffline);
1346 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001347
1348 for (Entry<ProviderId, DeviceDescriptions>
1349 prov : devDescs.entrySet()) {
1350
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001351 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001352 final ProviderId provId = prov.getKey();
1353 final DeviceDescriptions descs = prov.getValue();
1354
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001355 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001356 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001357
1358 for (Entry<PortNumber, Timestamped<PortDescription>>
1359 portDesc : descs.getPortDescs().entrySet()) {
1360
1361 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001362 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001363 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001364 }
1365 }
1366 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001367 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001368
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001369 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001370 }
1371
1372 /**
1373 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001374 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001375 * Notify sender about out-dated information using regular replication message.
1376 * Send back advertisement to sender if not in sync.
1377 *
1378 * @param advertisement to respond to
1379 */
1380 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1381
1382 final NodeId sender = advertisement.sender();
1383
1384 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1385 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1386 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1387
1388 // Fragments to request
1389 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1390 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1391
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001392 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001393 final DeviceId deviceId = de.getKey();
1394 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1395
1396 synchronized (lDevice) {
1397 // latestTimestamp across provider
1398 // Note: can be null initially
1399 Timestamp localLatest = offline.get(deviceId);
1400
1401 // handle device Ads
1402 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1403 final ProviderId provId = prov.getKey();
1404 final DeviceDescriptions lDeviceDescs = prov.getValue();
1405
1406 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1407
1408
1409 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1410 Timestamp advDevTimestamp = devAds.get(devFragId);
1411
Jonathan Hart403ea932015-02-20 16:23:00 -08001412 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1413 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001414 // remote does not have it or outdated, suggest
1415 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1416 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1417 // local is outdated, request
1418 reqDevices.add(devFragId);
1419 }
1420
1421 // handle port Ads
1422 for (Entry<PortNumber, Timestamped<PortDescription>>
1423 pe : lDeviceDescs.getPortDescs().entrySet()) {
1424
1425 final PortNumber num = pe.getKey();
1426 final Timestamped<PortDescription> lPort = pe.getValue();
1427
1428 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1429
1430 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001431 if (advPortTimestamp == null || lPort.isNewerThan(
1432 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001433 // remote does not have it or outdated, suggest
1434 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1435 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1436 // local is outdated, request
1437 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1438 reqPorts.add(portFragId);
1439 }
1440
1441 // remove port Ad already processed
1442 portAds.remove(portFragId);
1443 } // end local port loop
1444
1445 // remove device Ad already processed
1446 devAds.remove(devFragId);
1447
1448 // find latest and update
1449 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1450 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001451 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001452 localLatest = providerLatest;
1453 }
1454 } // end local provider loop
1455
1456 // checking if remote timestamp is more recent.
1457 Timestamp rOffline = offlineAds.get(deviceId);
jaegonkim73c21bd2018-01-13 10:52:02 +09001458 if (localLatest == null || (rOffline != null && rOffline.compareTo(localLatest) > 0)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001459 // remote offline timestamp suggests that the
1460 // device is off-line
1461 markOfflineInternal(deviceId, rOffline);
1462 }
1463
1464 Timestamp lOffline = offline.get(deviceId);
1465 if (lOffline != null && rOffline == null) {
1466 // locally offline, but remote is online, suggest offline
Palash Kala6c526062018-04-03 18:25:11 +09001467 notifyPeer(sender, new InternalDeviceStatusChangeEvent(deviceId, lOffline, false));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001468 }
1469
1470 // remove device offline Ad already processed
1471 offlineAds.remove(deviceId);
1472 } // end local device loop
1473 } // device lock
1474
1475 // If there is any Ads left, request them
1476 log.trace("Ads left {}, {}", devAds, portAds);
1477 reqDevices.addAll(devAds.keySet());
1478 reqPorts.addAll(portAds.keySet());
1479
1480 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1481 log.trace("Nothing to request to remote peer {}", sender);
1482 return;
1483 }
1484
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001485 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001486
1487 // 2-way Anti-Entropy for now
1488 try {
1489 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1490 } catch (IOException e) {
1491 log.error("Failed to send response advertisement to " + sender, e);
1492 }
1493
1494// Sketch of 3-way Anti-Entropy
1495// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1496// ClusterMessage message = new ClusterMessage(
1497// clusterService.getLocalNode().id(),
1498// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1499// SERIALIZER.encode(request));
1500//
1501// try {
1502// clusterCommunicator.unicast(message, advertisement.sender());
1503// } catch (IOException e) {
1504// log.error("Failed to send advertisement reply to "
1505// + advertisement.sender(), e);
1506// }
Madan Jampani47c93732014-10-06 20:46:08 -07001507 }
1508
Madan Jampani255a58b2014-10-09 12:08:20 -07001509 private void notifyDelegateIfNotNull(DeviceEvent event) {
1510 if (event != null) {
1511 notifyDelegate(event);
1512 }
1513 }
1514
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001515 private final class SendAdvertisementTask implements Runnable {
1516
1517 @Override
1518 public void run() {
1519 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001520 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001521 return;
1522 }
1523
1524 try {
1525 final NodeId self = clusterService.getLocalNode().id();
1526 Set<ControllerNode> nodes = clusterService.getNodes();
1527
1528 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1529 .transform(toNodeId())
1530 .toList();
1531
1532 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001533 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001534 return;
1535 }
1536
1537 NodeId peer;
1538 do {
1539 int idx = RandomUtils.nextInt(0, nodeIds.size());
1540 peer = nodeIds.get(idx);
1541 } while (peer.equals(self));
1542
1543 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1544
1545 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001546 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001547 return;
1548 }
1549
1550 try {
1551 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1552 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001553 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001554 return;
1555 }
1556 } catch (Exception e) {
1557 // catch all Exception to avoid Scheduled task being suppressed.
1558 log.error("Exception thrown while sending advertisement", e);
1559 }
1560 }
1561 }
1562
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001563 private void handleDeviceEvent(InternalDeviceEvent event) {
1564 ProviderId providerId = event.providerId();
1565 DeviceId deviceId = event.deviceId();
1566 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001567
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001568 try {
1569 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1570 deviceDescription));
1571 } catch (Exception e) {
1572 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001573 }
1574 }
1575
Palash Kala6c526062018-04-03 18:25:11 +09001576 private void handleDeviceStatusChangeEvent(InternalDeviceStatusChangeEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001577 DeviceId deviceId = event.deviceId();
1578 Timestamp timestamp = event.timestamp();
Palash Kala6c526062018-04-03 18:25:11 +09001579 Boolean available = event.available();
Madan Jampani25322532014-10-08 11:20:38 -07001580
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001581 try {
Palash Kala6c526062018-04-03 18:25:11 +09001582 if (available) {
1583 notifyDelegateIfNotNull(markOnlineInternal(deviceId, timestamp));
1584 } else {
1585 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1586 }
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001587 } catch (Exception e) {
Palash Kala6c526062018-04-03 18:25:11 +09001588 log.warn("Exception thrown handling device status change event", e);
Madan Jampani25322532014-10-08 11:20:38 -07001589 }
1590 }
1591
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001592 private void handleRemoveRequest(DeviceId did) {
1593 try {
Jayasree Ghosh7d96d6a2017-02-27 18:35:32 +05301594 DeviceEvent event = removeDevice(did);
1595 notifyDelegateIfNotNull(event);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001596 } catch (Exception e) {
1597 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001598 }
1599 }
1600
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001601 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1602 DeviceId deviceId = event.deviceId();
1603 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001604
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001605 try {
1606 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1607 } catch (Exception e) {
1608 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001609 }
1610 }
1611
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001612 private void handlePortEvent(InternalPortEvent event) {
1613 ProviderId providerId = event.providerId();
1614 DeviceId deviceId = event.deviceId();
1615 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001616
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001617 if (getDevice(deviceId) == null) {
1618 log.debug("{} not found on this node yet, ignoring.", deviceId);
1619 // Note: dropped information will be recovered by anti-entropy
1620 return;
1621 }
Madan Jampani47c93732014-10-06 20:46:08 -07001622
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001623 try {
1624 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1625 } catch (Exception e) {
1626 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001627 }
1628 }
1629
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001630 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1631 ProviderId providerId = event.providerId();
1632 DeviceId deviceId = event.deviceId();
1633 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001634
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001635 if (getDevice(deviceId) == null) {
1636 log.debug("{} not found on this node yet, ignoring.", deviceId);
1637 // Note: dropped information will be recovered by anti-entropy
1638 return;
1639 }
Madan Jampani47c93732014-10-06 20:46:08 -07001640
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001641 try {
1642 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1643 } catch (Exception e) {
1644 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001645 }
1646 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001647
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001648 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1649 try {
1650 handleAdvertisement(advertisement);
1651 } catch (Exception e) {
1652 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001653 }
1654 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001655
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001656 private class InternalPortStatsListener
1657 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1658 @Override
1659 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1660 if (event.type() == PUT) {
1661 Device device = devices.get(event.key());
1662 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001663 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001664 }
1665 }
1666 }
1667 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001668}