blob: 2bd4dfe38dad20131241a9556e71788f5b8965b5 [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;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080023import org.onlab.packet.ChassisId;
24import org.onlab.util.KryoNamespace;
Brian O'Connorabafb502014-12-02 22:26:20 -080025import org.onosproject.cluster.ClusterService;
26import org.onosproject.cluster.ControllerNode;
27import org.onosproject.cluster.NodeId;
28import org.onosproject.mastership.MastershipService;
Brian O'Connorabafb502014-12-02 22:26:20 -080029import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070030import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080031import org.onosproject.net.AnnotationsUtil;
32import org.onosproject.net.DefaultAnnotations;
33import org.onosproject.net.DefaultDevice;
34import org.onosproject.net.DefaultPort;
35import org.onosproject.net.Device;
36import org.onosproject.net.Device.Type;
37import org.onosproject.net.DeviceId;
38import org.onosproject.net.MastershipRole;
39import org.onosproject.net.Port;
40import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070041import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080042import org.onosproject.net.device.DeviceClockService;
43import org.onosproject.net.device.DeviceDescription;
44import org.onosproject.net.device.DeviceEvent;
45import org.onosproject.net.device.DeviceStore;
46import org.onosproject.net.device.DeviceStoreDelegate;
47import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070048import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080049import org.onosproject.net.provider.ProviderId;
50import org.onosproject.store.AbstractStore;
51import org.onosproject.store.Timestamp;
52import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
Brian O'Connorabafb502014-12-02 22:26:20 -080053import org.onosproject.store.cluster.messaging.MessageSubject;
Jordan Haltermanebedbb52017-08-08 15:57:50 -070054import org.onosproject.store.impl.MastershipBasedTimestamp;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070056import org.onosproject.store.serializers.KryoNamespaces;
Brian O'Connor6de2e202015-05-21 14:30:41 -070057import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070058import org.onosproject.store.service.EventuallyConsistentMap;
59import org.onosproject.store.service.EventuallyConsistentMapEvent;
60import org.onosproject.store.service.EventuallyConsistentMapListener;
61import org.onosproject.store.service.MultiValuedTimestamp;
Jordan Halterman2c83a102017-08-20 17:11:41 -070062import org.onosproject.store.service.Serializer;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070063import org.onosproject.store.service.StorageService;
64import org.onosproject.store.service.WallClockTimestamp;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070065import org.osgi.service.component.annotations.Activate;
66import org.osgi.service.component.annotations.Component;
67import org.osgi.service.component.annotations.Deactivate;
68import org.osgi.service.component.annotations.Reference;
69import org.osgi.service.component.annotations.ReferenceCardinality;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070070import org.slf4j.Logger;
71
Thomas Vachuskaa651de12018-04-19 12:11:09 -070072import java.io.IOException;
73import java.util.ArrayList;
74import java.util.Collection;
75import java.util.Collections;
76import java.util.HashMap;
77import java.util.HashSet;
78import java.util.Iterator;
79import java.util.List;
80import java.util.Map;
81import java.util.Map.Entry;
82import java.util.Objects;
83import java.util.Optional;
84import java.util.Set;
85import java.util.concurrent.ConcurrentHashMap;
86import java.util.concurrent.ConcurrentMap;
87import java.util.concurrent.ExecutorService;
88import java.util.concurrent.ScheduledExecutorService;
89import java.util.concurrent.TimeUnit;
90import java.util.function.Consumer;
91import java.util.stream.Stream;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070092
93import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070094import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070095import static com.google.common.base.Verify.verify;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -080096import static java.util.concurrent.Executors.newCachedThreadPool;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080097import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080098import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -080099import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800100import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700101import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED;
102import static org.onosproject.net.device.DeviceEvent.Type.PORT_ADDED;
103import static org.onosproject.net.device.DeviceEvent.Type.PORT_REMOVED;
104import static org.onosproject.net.device.DeviceEvent.Type.PORT_STATS_UPDATED;
105import static org.onosproject.net.device.DeviceEvent.Type.PORT_UPDATED;
106import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700107import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVED;
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700108import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
109import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE;
110import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_UPDATE;
111import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE;
112import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_UPDATE;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700113import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800114import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700115
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700116/**
117 * Manages inventory of infrastructure devices using gossip protocol to distribute
118 * information.
119 */
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700120@Component(immediate = true, service = DeviceStore.class)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700121public class GossipDeviceStore
122 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
123 implements DeviceStore {
124
125 private final Logger log = getLogger(getClass());
126
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700127 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800128 // Timeout in milliseconds to process device or ports on remote master node
129 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700130
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700131 // innerMap is used to lock a Device, thus instance should never be replaced.
132 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700133 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700134 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700135
136 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700137 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
138 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700139
140 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200141 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700142 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
143 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700144
145 // to be updated under Device lock
146 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
147 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700148
149 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700150 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700151
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700152 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700153 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700154
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700155 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700156 protected StorageService storageService;
157
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700158 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Madan Jampani47c93732014-10-06 20:46:08 -0700159 protected ClusterCommunicationService clusterCommunicator;
160
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700161 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Madan Jampani53e44e62014-10-07 12:39:51 -0700162 protected ClusterService clusterService;
163
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700164 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700165 protected MastershipService mastershipService;
166
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700167 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800168 protected MastershipTermService termService;
169
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700170 private static final Timestamp DEFAULT_TIMESTAMP = new MastershipBasedTimestamp(0, 0);
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800171
Jordan Halterman2c83a102017-08-20 17:11:41 -0700172 protected static final Serializer SERIALIZER = Serializer.using(KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800173 .register(DistributedStoreSerializers.STORE_COMMON)
174 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
175 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
Palash Kala6c526062018-04-03 18:25:11 +0900176 .register(new InternalDeviceStatusChangeEventSerializer(), InternalDeviceStatusChangeEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700177 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800178 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
179 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700180 .register(DeviceAntiEntropyAdvertisement.class)
181 .register(DeviceFragmentId.class)
182 .register(PortFragmentId.class)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700183 .build("GossipDevice"));
Madan Jampani53e44e62014-10-07 12:39:51 -0700184
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800185 private ExecutorService executor;
186
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800187 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700188
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800189 // TODO make these anti-entropy parameters configurable
190 private long initialDelaySec = 5;
191 private long periodSec = 5;
192
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700193 @Activate
194 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800195 executor = newCachedThreadPool(groupedThreads("onos/device", "fg-%d", log));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800196
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800197 backgroundExecutor =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800198 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d", log)));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700199
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700200 addSubscriber(DEVICE_UPDATE, this::handleDeviceEvent);
Palash Kala6c526062018-04-03 18:25:11 +0900201 addSubscriber(DEVICE_STATUS_CHANGE, this::handleDeviceStatusChangeEvent);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700202 addSubscriber(DEVICE_REMOVE_REQ, this::handleRemoveRequest);
203 addSubscriber(DEVICE_REMOVED, this::handleDeviceRemovedEvent);
204 addSubscriber(PORT_UPDATE, this::handlePortEvent);
205 addSubscriber(PORT_STATUS_UPDATE, this::handlePortStatusEvent);
206 addSubscriber(DEVICE_ADVERTISE, this::handleDeviceAdvertisement);
Madan Jampani2af244a2015-02-22 13:12:01 -0800207
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700208 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800209 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700210 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700211
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700212 // Create a distributed map for port stats.
213 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
214 .register(KryoNamespaces.API)
HIGUCHI Yuta03666a32016-05-18 11:49:09 -0700215 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
216 .register(MultiValuedTimestamp.class);
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700217
218 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
219 .withName("port-stats")
220 .withSerializer(deviceDataSerializer)
221 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700222 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700223 .withTombstonesDisabled()
224 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200225 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
226 eventuallyConsistentMapBuilder()
227 .withName("port-stats-delta")
228 .withSerializer(deviceDataSerializer)
229 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
230 .withTimestampProvider((k, v) -> new WallClockTimestamp())
231 .withTombstonesDisabled()
232 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700233 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700234 log.info("Started");
235 }
236
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700237 private <M> void addSubscriber(MessageSubject subject, Consumer<M> handler) {
238 clusterCommunicator.addSubscriber(subject, SERIALIZER::decode, handler, executor);
239 }
240
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700241 @Deactivate
242 public void deactivate() {
Frank Wange0eb5ce2016-07-01 18:21:25 +0800243 devicePortStats.removeListener(portStatsListener);
Madan Jampani632f16b2015-08-11 12:42:59 -0700244 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200245 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800246 executor.shutdownNow();
247
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800248 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700249 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800250 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700251 log.error("Timeout during executor shutdown");
252 }
253 } catch (InterruptedException e) {
254 log.error("Error during executor shutdown", e);
Ray Milkey5c7d4882018-02-05 14:50:39 -0800255 Thread.currentThread().interrupt();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700256 }
257
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700258 deviceDescs.clear();
259 devices.clear();
260 devicePorts.clear();
261 availableDevices.clear();
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700262 clusterCommunicator.removeSubscriber(DEVICE_UPDATE);
Palash Kala6c526062018-04-03 18:25:11 +0900263 clusterCommunicator.removeSubscriber(DEVICE_STATUS_CHANGE);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700264 clusterCommunicator.removeSubscriber(DEVICE_REMOVE_REQ);
265 clusterCommunicator.removeSubscriber(DEVICE_REMOVED);
266 clusterCommunicator.removeSubscriber(PORT_UPDATE);
267 clusterCommunicator.removeSubscriber(PORT_STATUS_UPDATE);
268 clusterCommunicator.removeSubscriber(DEVICE_ADVERTISE);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700269 log.info("Stopped");
270 }
271
272 @Override
273 public int getDeviceCount() {
274 return devices.size();
275 }
276
277 @Override
mskala0d0c6832017-07-12 11:21:23 +0200278 public int getAvailableDeviceCount() {
279 return availableDevices.size();
280 }
281
282 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700283 public Iterable<Device> getDevices() {
284 return Collections.unmodifiableCollection(devices.values());
285 }
286
287 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800288 public Iterable<Device> getAvailableDevices() {
289 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700290 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800291 }
292
293 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700294 public Device getDevice(DeviceId deviceId) {
295 return devices.get(deviceId);
296 }
297
298 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700299 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700300 DeviceId deviceId,
301 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800302 NodeId localNode = clusterService.getLocalNode().id();
303 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Jordan Haltermanf9f55632017-12-19 14:56:08 -0800304 boolean isMaster = localNode.equals(deviceNode);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800305
306 // Process device update only if we're the master,
307 // otherwise signal the actual master.
308 DeviceEvent deviceEvent = null;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800309
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700310 // If this node is the master for the device, acquire a new timestamp. Otherwise,
311 // use a 0,0 or tombstone timestamp to create the device if it doesn't already exist.
Jordan Haltermanf9f55632017-12-19 14:56:08 -0800312 Timestamp newTimestamp;
313 try {
314 newTimestamp = isMaster
315 ? deviceClockService.getTimestamp(deviceId)
316 : removalRequest.getOrDefault(deviceId, DEFAULT_TIMESTAMP);
317 } catch (IllegalStateException e) {
Yuta HIGUCHIfbd9ae92018-01-24 23:39:06 -0800318 newTimestamp = removalRequest.getOrDefault(deviceId, DEFAULT_TIMESTAMP);
Jordan Haltermanf9f55632017-12-19 14:56:08 -0800319 isMaster = false;
320 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700321 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
322 final Timestamped<DeviceDescription> mergedDesc;
323 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800324
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700325 synchronized (device) {
326 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
Jordan Halterman8a0b3972017-08-15 16:14:18 -0700327 if (deviceEvent == null) {
328 return null;
329 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700330 mergedDesc = device.get(providerId).getDeviceDesc();
331 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800332
pier388ec252020-04-15 20:53:14 +0200333 // If this node is the master for the device, update peers.
334 if (isMaster) {
335 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
336 providerId, deviceId);
337 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
338 }
Andrea Campanellabba1e882018-05-14 18:17:28 +0200339 notifyDelegateIfNotNull(deviceEvent);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800340
341 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700342 }
343
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700344 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700345 DeviceId deviceId,
346 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700347
348 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800349 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700350 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700351
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800352 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700353 // locking per device
354
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700355 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
356 log.debug("Ignoring outdated event: {}", deltaDesc);
357 return null;
358 }
359
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800360 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700361
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700362 final Device oldDevice = devices.get(deviceId);
363 final Device newDevice;
364
365 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700366 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700367 // on new device or valid update
368 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800369 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700370 } else {
371 // outdated event, ignored.
372 return null;
373 }
Thomas Vachuskaf131e592018-05-07 11:52:14 -0700374
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700375 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700376 // REGISTER
377 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700378 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700379 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700380 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700381 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700382 } else {
383 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700384 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
385 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700386 }
387 }
388 }
389
390 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700391 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700392 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700393 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700394
395 // update composed device cache
396 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
397 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700398 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
399 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700400
401 if (!providerId.isAncillary()) {
Palash Kala6c526062018-04-03 18:25:11 +0900402 markOnline(newDevice.id(), timestamp, false);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700403 }
404
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700405 log.debug("Device {} added", newDevice.id());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700406 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
407 }
408
409 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700410 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700411 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700412 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700413 Device newDevice, Timestamp newTimestamp,
414 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700415 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700416 boolean propertiesChanged =
417 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700418 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
mskala4b2081a2017-06-12 16:39:50 +0200419 !Objects.equals(oldDevice.providerId(), newDevice.providerId()) ||
gyewan.an4fd2b8a2019-04-25 16:59:26 +0900420 !Objects.equals(oldDevice.chassisId(), newDevice.chassisId()) ||
421 !Objects.equals(oldDevice.serialNumber(), newDevice.serialNumber()) ||
422 !Objects.equals(oldDevice.manufacturer(), newDevice.manufacturer());
423
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700424 boolean annotationsChanged =
425 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700426
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700427 // Primary providers can respond to all changes, but ancillary ones
428 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800429 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700430 if ((providerId.isAncillary() && annotationsChanged) ||
431 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700432 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
433 if (!replaced) {
434 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700435 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800436 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700437 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700438
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700439 log.debug("Device {} updated", newDevice.id());
alshabibdc5d8bd2015-11-02 15:41:29 -0800440 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700441 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800442
helenyrwufd296b62016-06-22 17:43:02 -0700443 if (!providerId.isAncillary() && forceAvailable) {
Palash Kala6c526062018-04-03 18:25:11 +0900444 notifyDelegateIfNotNull(markOnline(newDevice.id(), newTimestamp, false));
alshabibdc5d8bd2015-11-02 15:41:29 -0800445 }
446 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700447 }
448
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700449 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700450 // update composed device cache
451 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
452 verify(oldDevice == null,
453 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
454 providerId, oldDevice, newDevice);
455
456 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700457 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700458 }
459
460 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
461 }
462
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700463 @Override
464 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700465 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
466 }
467
468 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700469 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700470 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700471 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700472 deviceId, timestamp);
Palash Kala6c526062018-04-03 18:25:11 +0900473 notifyPeers(new InternalDeviceStatusChangeEvent(deviceId, timestamp, false));
Madan Jampani25322532014-10-08 11:20:38 -0700474 }
475 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700476 }
477
478 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700479 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700480 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700481
482 // locking device
483 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700484 // accept off-line if given timestamp is newer than
485 // the latest Timestamp from Primary provider
486 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
jaegonkim73c21bd2018-01-13 10:52:02 +0900487 if (primDescs != null) {
488 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
489 if (lastTimestamp == null) {
490 lastTimestamp = deviceClockService.getTimestamp(deviceId);
491 }
492 if (timestamp.compareTo(lastTimestamp) <= 0) {
493 // outdated event ignore
494 return null;
495 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700496 }
497
498 offline.put(deviceId, timestamp);
499
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700500 Device device = devices.get(deviceId);
501 if (device == null) {
Andrea Campanellabba1e882018-05-14 18:17:28 +0200502 // Single Instance ONOS, device is removed from devices map and is null here but
503 // must still be marked offline
504 availableDevices.remove(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700505 return null;
506 }
507 boolean removed = availableDevices.remove(deviceId);
508 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700509 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700510 }
511 return null;
512 }
513 }
514
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700515 @Override
Palash Kala6c526062018-04-03 18:25:11 +0900516 public DeviceEvent markOnline(DeviceId deviceId) {
517 return markOnline(deviceId, deviceClockService.getTimestamp(deviceId), true);
helenyrwufd296b62016-06-22 17:43:02 -0700518 }
519
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700520 /**
521 * Marks the device as available if the given timestamp is not outdated,
522 * compared to the time the device has been marked offline.
523 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700524 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700525 * @param timestamp of the event triggering this change.
Palash Kala6c526062018-04-03 18:25:11 +0900526 * @param notifyPeers if the event needs to be notified to peers.
527 * @return ready to send event describing what occurred; null if no change
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700528 */
Palash Kala6c526062018-04-03 18:25:11 +0900529 private DeviceEvent markOnline(DeviceId deviceId, Timestamp timestamp, boolean notifyPeers) {
530 final DeviceEvent event = markOnlineInternal(deviceId, timestamp);
531 if (event != null && notifyPeers) {
532 log.debug("Notifying peers of a device online topology event for deviceId: {} {}",
533 deviceId, timestamp);
534 notifyPeers(new InternalDeviceStatusChangeEvent(deviceId, timestamp, true));
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700535 }
Palash Kala6c526062018-04-03 18:25:11 +0900536 return event;
537 }
538
539 // Guarded by deviceDescs value (=Device lock)
540 private DeviceEvent markOnlineInternal(DeviceId deviceId, Timestamp timestamp) {
541 if (devices.containsKey(deviceId)) {
542 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
543 synchronized (deviceLock) {
544 // accept on-line if given timestamp is newer than
545 // the latest offline request Timestamp
546 Timestamp offlineTimestamp = offline.get(deviceId);
547 if (offlineTimestamp == null ||
548 offlineTimestamp.compareTo(timestamp) < 0) {
549 offline.remove(deviceId);
550 Device device = devices.get(deviceId);
551 boolean add = availableDevices.add(deviceId);
552 if (add) {
553 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
554 }
555 }
556 }
Thomas Vachuskae36a2822018-05-03 12:16:52 -0700557 } else {
558 log.warn("Device {} does not exist in store", deviceId);
Palash Kala6c526062018-04-03 18:25:11 +0900559 }
Palash Kala6c526062018-04-03 18:25:11 +0900560 return null;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700561 }
562
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700563 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700564 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700565 DeviceId deviceId,
566 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700567
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800568 NodeId localNode = clusterService.getLocalNode().id();
569 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
570 // since it will trigger distributed store read.
571 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
572 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
573 // If we don't care much about topology performance, then it might be OK.
574 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700575
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800576 // Process port update only if we're the master of the device,
577 // otherwise signal the actual master.
578 List<DeviceEvent> deviceEvents = null;
579 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700580
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800581 final Timestamp newTimestamp;
582 try {
583 newTimestamp = deviceClockService.getTimestamp(deviceId);
584 } catch (IllegalStateException e) {
585 log.info("Timestamp was not available for device {}", deviceId);
586 log.debug(" discarding {}", portDescriptions);
587 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700588
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800589 // Possible situation:
590 // Device connected and became master for short period of time,
591 // but lost mastership before this instance had the chance to
592 // retrieve term information.
593
594 // Information dropped here is expected to be recoverable by
595 // device probing after mastership change
596
597 return Collections.emptyList();
598 }
599 log.debug("timestamp for {} {}", deviceId, newTimestamp);
600
601 final Timestamped<List<PortDescription>> timestampedInput
602 = new Timestamped<>(portDescriptions, newTimestamp);
603 final Timestamped<List<PortDescription>> merged;
604
605 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
606
607 synchronized (device) {
608 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
609 final DeviceDescriptions descs = device.get(providerId);
610 List<PortDescription> mergedList =
611 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700612 .transform(input ->
613 // lookup merged port description
614 descs.getPortDesc(input.portNumber()).value()
615 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700616 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800617 }
618
619 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700620 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700621 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800622 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
623 }
624
625 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700626 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700627 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700628
Ray Milkeyfe0e0852018-01-18 11:14:05 -0800629 return deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700630 }
631
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700632 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700633 DeviceId deviceId,
634 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700635
636 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700637 if (device == null) {
638 log.debug("Device is no longer valid: {}", deviceId);
639 return Collections.emptyList();
640 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700641
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700642 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700643 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
644
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700645 List<DeviceEvent> events = new ArrayList<>();
646 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700647
648 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
649 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700650 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700651 }
652
653 DeviceDescriptions descs = descsMap.get(providerId);
654 // every provider must provide DeviceDescription.
655 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700656 "Device description for Device ID %s from Provider %s was not found",
657 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700658
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700659 Map<PortNumber, Port> ports = getPortMap(deviceId);
660
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700661 final Timestamp newTimestamp = portDescriptions.timestamp();
662
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700663 // Add new ports
664 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700665 for (PortDescription portDescription : portDescriptions.value()) {
666 final PortNumber number = portDescription.portNumber();
667 processed.add(number);
668
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700669 final Port oldPort = ports.get(number);
670 final Port newPort;
Palash Kala8d30b612018-03-02 11:06:10 +0900671 boolean isRemoved = portDescription.isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700672
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700673
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700674 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
675 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700676 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700677 // on new port or valid update
678 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700679 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700680 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700681 newPort = composePort(device, number, descsMap);
682 } else {
683 // outdated event, ignored.
684 continue;
685 }
686
Palash Kala8d30b612018-03-02 11:06:10 +0900687 if (isRemoved && oldPort != null) {
Andrea Campanellab0dfbc82020-08-10 18:06:42 +0200688 events.add(removePort(deviceId, oldPort.number(), providerId, descsMap));
Palash Kala8d30b612018-03-02 11:06:10 +0900689 } else if (!isRemoved) {
690 events.add(oldPort == null ?
691 createPort(device, newPort, ports) :
692 updatePort(device, oldPort, newPort, ports));
693 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700694 }
695
696 events.addAll(pruneOldPorts(device, ports, processed));
697 }
698 return FluentIterable.from(events).filter(notNull()).toList();
699 }
700
701 // Creates a new port based on the port description adds it to the map and
702 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700703 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700704 private DeviceEvent createPort(Device device, Port newPort,
705 Map<PortNumber, Port> ports) {
706 ports.put(newPort.number(), newPort);
707 return new DeviceEvent(PORT_ADDED, device, newPort);
708 }
709
710 // Checks if the specified port requires update and if so, it replaces the
711 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700712 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700713 private DeviceEvent updatePort(Device device, Port oldPort,
714 Port newPort,
715 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100716
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700717 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700718 oldPort.type() != newPort.type() ||
719 oldPort.portSpeed() != newPort.portSpeed() ||
720 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700721 ports.put(oldPort.number(), newPort);
722 return new DeviceEvent(PORT_UPDATED, device, newPort);
723 }
724 return null;
725 }
726
Andrea Campanellab0dfbc82020-08-10 18:06:42 +0200727 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber,
728 ProviderId providerId, Map<ProviderId, DeviceDescriptions> descsMap) {
Michal Machce774332017-01-25 11:02:55 +0100729
730 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
731 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
732
Andrea Campanellab0dfbc82020-08-10 18:06:42 +0200733 descsMap.computeIfPresent(providerId, (provider, deviceDescriptions) -> {
734 deviceDescriptions.removePortDesc(portNumber);
735 return deviceDescriptions;
736 });
Michal Machce774332017-01-25 11:02:55 +0100737 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
738 }
739
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700740 // Prunes the specified list of ports based on which ports are in the
741 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700742 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700743 private List<DeviceEvent> pruneOldPorts(Device device,
744 Map<PortNumber, Port> ports,
745 Set<PortNumber> processed) {
746 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700747 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700748 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700749 Entry<PortNumber, Port> e = iterator.next();
750 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700751 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700752 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700753 iterator.remove();
754 }
755 }
756 return events;
757 }
758
759 // Gets the map of ports for the specified device; if one does not already
760 // exist, it creates and registers a new one.
761 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700762 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700763 }
764
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700765 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700766 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700767 Map<ProviderId, DeviceDescriptions> r;
768 r = deviceDescs.get(deviceId);
769 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700770 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700771 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
772 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
773 if (concurrentlyAdded != null) {
774 r = concurrentlyAdded;
775 }
776 }
777 return r;
778 }
779
780 // Guarded by deviceDescs value (=Device lock)
781 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
782 Map<ProviderId, DeviceDescriptions> device,
783 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700784 synchronized (device) {
785 DeviceDescriptions r = device.get(providerId);
786 if (r == null) {
787 r = new DeviceDescriptions(deltaDesc);
788 device.put(providerId, r);
789 }
790 return r;
791 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700792 }
793
794 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700795 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
796 DeviceId deviceId,
797 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700798 final Timestamp newTimestamp;
799 try {
800 newTimestamp = deviceClockService.getTimestamp(deviceId);
801 } catch (IllegalStateException e) {
802 log.info("Timestamp was not available for device {}", deviceId);
803 log.debug(" discarding {}", portDescription);
804 // Failed to generate timestamp. Ignoring.
805 // See updatePorts comment
806 return null;
807 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700808 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700809 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700810 final DeviceEvent event;
Andrea Campanellab0dfbc82020-08-10 18:06:42 +0200811 Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800812 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
813 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700814 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800815 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700816 .getPortDesc(portDescription.portNumber());
Andrea Campanellab0dfbc82020-08-10 18:06:42 +0200817 //on delete the port is removed, thus using latest known description
818 if (mergedDesc == null) {
819 mergedDesc = new Timestamped<>(portDescription, newTimestamp);
820 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700821 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700822 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700823 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700824 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800825 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700826 }
827 return event;
828 }
829
830 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700831 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700832 Device device = devices.get(deviceId);
833 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
834
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700835 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700836 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
837
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700838 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700839
840 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
841 log.debug("Ignoring outdated event: {}", deltaDesc);
842 return null;
843 }
844
845 DeviceDescriptions descs = descsMap.get(providerId);
846 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700847 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700848 "Device description for Device ID %s from Provider %s was not found",
849 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700850
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700851 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
852 final PortNumber number = deltaDesc.value().portNumber();
853 final Port oldPort = ports.get(number);
854 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700855 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Andrea Campanellab0dfbc82020-08-10 18:06:42 +0200856 boolean toDelete;
Michal Machce774332017-01-25 11:02:55 +0100857
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700858 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700859 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700860 // on new port or valid update
861 // update description
862 descs.putPortDesc(deltaDesc);
863 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100864 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700865 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700866 // same or outdated event, ignored.
867 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700868 return null;
869 }
870
Andrea Campanellab0dfbc82020-08-10 18:06:42 +0200871 if (!toDelete) {
872 return oldPort == null ? createPort(device, newPort, ports) :
873 updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700874 } else {
Andrea Campanellab0dfbc82020-08-10 18:06:42 +0200875 return removePort(deviceId, number, providerId, descsMap);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700876 }
877 }
878 }
879
880 @Override
881 public List<Port> getPorts(DeviceId deviceId) {
882 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
883 if (ports == null) {
884 return Collections.emptyList();
885 }
886 return ImmutableList.copyOf(ports.values());
887 }
888
889 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700890 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
891 DeviceId deviceId) {
892 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
893 if (descs == null) {
Donghyeok Ho6de4fb92018-01-31 11:04:19 +0900894 return Stream.empty();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700895 }
896 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
897 final Optional<DeviceDescriptions> devDescs;
898 synchronized (descs) {
899 devDescs = Optional.ofNullable(descs.get(pid));
900 }
901 // DeviceDescriptions is concurrent access-safe
902 return devDescs
903 .map(dd -> dd.getPortDescs().values().stream()
904 .map(Timestamped::value))
905 .orElse(Stream.empty());
906 }
907
908 @Override
sangho538108b2015-04-08 14:29:20 -0700909 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200910 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700911
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200912 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
913 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
914 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
915
916 if (prvStatsMap != null) {
917 for (PortStatistics newStats : newStatsCollection) {
Ray Milkey5ec42082019-02-13 09:56:07 -0800918 PortNumber port = newStats.portNumber();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200919 PortStatistics prvStats = prvStatsMap.get(port);
920 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
921 PortStatistics deltaStats = builder.build();
922 if (prvStats != null) {
923 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
924 }
925 deltaStatsMap.put(port, deltaStats);
926 newStatsMap.put(port, newStats);
927 }
928 } else {
929 for (PortStatistics newStats : newStatsCollection) {
Ray Milkey5ec42082019-02-13 09:56:07 -0800930 PortNumber port = newStats.portNumber();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200931 newStatsMap.put(port, newStats);
932 }
sangho538108b2015-04-08 14:29:20 -0700933 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200934 devicePortDeltaStats.put(deviceId, deltaStatsMap);
935 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200936 // DeviceEvent returns null because of InternalPortStatsListener usage
937 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200938 }
939
940 /**
941 * Calculate delta statistics by subtracting previous from new statistics.
942 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700943 * @param deviceId device identifier
944 * @param prvStats previous port statistics
945 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200946 * @return PortStatistics
947 */
948 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
949 // calculate time difference
950 long deltaStatsSec, deltaStatsNano;
951 if (newStats.durationNano() < prvStats.durationNano()) {
952 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
953 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
954 } else {
955 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
956 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
957 }
958 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
959 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
Ray Milkey5ec42082019-02-13 09:56:07 -0800960 .setPort(newStats.portNumber())
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200961 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
962 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
963 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
964 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
965 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
966 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
967 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
968 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
969 .setDurationSec(deltaStatsSec)
970 .setDurationNano(deltaStatsNano)
971 .build();
972 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700973 }
974
975 @Override
976 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700977 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
978 if (portStats == null) {
979 return Collections.emptyList();
980 }
981 return ImmutableList.copyOf(portStats.values());
982 }
983
984 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530985 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
986 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
987 if (portStatsMap == null) {
988 return null;
989 }
990 PortStatistics portStats = portStatsMap.get(portNumber);
991 return portStats;
992 }
993
994 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200995 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
996 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
997 if (portStats == null) {
998 return Collections.emptyList();
999 }
1000 return ImmutableList.copyOf(portStats.values());
1001 }
1002
1003 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +05301004 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
1005 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
1006 if (portStatsMap == null) {
1007 return null;
1008 }
1009 PortStatistics portStats = portStatsMap.get(portNumber);
1010 return portStats;
1011 }
1012
1013 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001014 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
1015 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1016 return ports == null ? null : ports.get(portNumber);
1017 }
1018
1019 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -07001020 public PortDescription getPortDescription(ProviderId pid,
1021 DeviceId deviceId,
1022 PortNumber portNumber) {
1023 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1024 if (descs == null) {
1025 return null;
1026 }
1027 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1028 final Optional<DeviceDescriptions> devDescs;
1029 synchronized (descs) {
1030 devDescs = Optional.ofNullable(descs.get(pid));
1031 }
1032 // DeviceDescriptions is concurrent access-safe
1033 return devDescs
1034 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1035 .map(Timestamped::value)
1036 .orElse(null);
1037 }
1038
1039 @Override
pierventree1f80102021-10-01 22:01:22 +02001040 public DeviceDescription getDeviceDescription(ProviderId providerId, DeviceId deviceId) {
1041 if (devices.containsKey(deviceId)) {
1042 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
1043 synchronized (descs) {
1044 DeviceDescriptions deviceDescriptions = descs.get(providerId);
1045 return deviceDescriptions != null ? deviceDescriptions.getDeviceDesc().value() : null;
1046 }
1047 } else {
1048 log.warn("Device {} does not exist in store", deviceId);
1049 }
1050 return null;
1051 }
1052
1053 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001054 public boolean isAvailable(DeviceId deviceId) {
1055 return availableDevices.contains(deviceId);
1056 }
1057
1058 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001059 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001060 final NodeId myId = clusterService.getLocalNode().id();
1061 NodeId master = mastershipService.getMasterFor(deviceId);
1062
1063 // if there exist a master, forward
1064 // if there is no master, try to become one and process
1065
1066 boolean relinquishAtEnd = false;
1067 if (master == null) {
1068 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1069 if (myRole != MastershipRole.NONE) {
1070 relinquishAtEnd = true;
1071 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001072 log.debug("Temporarily requesting role for {} to remove", deviceId);
Jordan Haltermanf1c602d2017-10-18 11:26:52 -07001073 if (mastershipService.requestRoleFor(deviceId).join() == MastershipRole.MASTER) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001074 master = myId;
1075 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001076 }
1077
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001078 boolean isMaster = myId.equals(master);
1079
1080 // If this node is not the master, forward the request.
1081 if (!isMaster) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001082 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001083 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001084
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001085 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001086 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001087 /* error log:
1088 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1089 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001090 }
1091
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001092 // If this node is the master, get a timestamp. Otherwise, default to the current device timestamp.
1093 Timestamp timestamp = isMaster ? deviceClockService.getTimestamp(deviceId) : null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001094
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001095 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001096
1097 // If this node is the master, update peers.
1098 if (isMaster && event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001099 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001100 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001101 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001102 }
pier388ec252020-04-15 20:53:14 +02001103 notifyDelegateIfNotNull(event);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001104
1105 // Relinquish mastership if acquired to remove the device.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001106 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001107 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001108 mastershipService.relinquishMastership(deviceId);
1109 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001110 return event;
1111 }
1112
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001113 private DeviceEvent removeDeviceInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001114
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001115 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001116 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001117 // accept removal request if given timestamp is newer than
1118 // the latest Timestamp from Primary provider
1119 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001120 if (primDescs == null) {
1121 return null;
1122 }
1123
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001124 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001125
1126 // If no timestamp is set, default the timestamp to the last timestamp for the device.
1127 if (timestamp == null) {
1128 timestamp = lastTimestamp;
1129 }
1130
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001131 if (timestamp.compareTo(lastTimestamp) <= 0) {
1132 // outdated event ignore
1133 return null;
1134 }
1135 removalRequest.put(deviceId, timestamp);
1136
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001137 Device device = devices.remove(deviceId);
Andrea Campanellab0dfbc82020-08-10 18:06:42 +02001138 //removing internal description
1139 deviceDescs.remove(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001140 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001141 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1142 if (ports != null) {
1143 ports.clear();
1144 }
1145 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001146 descs.clear();
pier388ec252020-04-15 20:53:14 +02001147 // Forget about the device
1148 offline.remove(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001149 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001150 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001151 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001152 }
1153
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001154 /**
1155 * Checks if given timestamp is superseded by removal request
1156 * with more recent timestamp.
1157 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001158 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001159 * @param timestampToCheck timestamp of an event to check
1160 * @return true if device is already removed
1161 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001162 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1163 Timestamp removalTimestamp = removalRequest.get(deviceId);
1164 if (removalTimestamp != null &&
Jordan Halterman8a0b3972017-08-15 16:14:18 -07001165 removalTimestamp.compareTo(timestampToCheck) > 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001166 // removalRequest is more recent
1167 return true;
1168 }
1169 return false;
1170 }
1171
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001172 /**
1173 * Returns a Device, merging description given from multiple Providers.
1174 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001175 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001176 * @param providerDescs Collection of Descriptions from multiple providers
1177 * @return Device instance
1178 */
1179 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001180 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001181
Thomas Vachuska444eda62014-10-28 13:09:42 -07001182 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001183
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001184 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001185
1186 DeviceDescriptions desc = providerDescs.get(primary);
1187
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001188 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001189 Type type = base.type();
1190 String manufacturer = base.manufacturer();
1191 String hwVersion = base.hwVersion();
1192 String swVersion = base.swVersion();
1193 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001194 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001195 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1196 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001197
1198 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1199 if (e.getKey().equals(primary)) {
1200 continue;
1201 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001202 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001203 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001204 // Currently assuming there will never be a key conflict between
1205 // providers
1206
1207 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001208 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001209 }
1210
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001211 return new DefaultDevice(primary, deviceId, type, manufacturer,
1212 hwVersion, swVersion, serialNumber,
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001213 chassisId, annotations.buildCompressed());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001214 }
1215
Marc De Leenheer88194c32015-05-29 22:10:59 -07001216 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1217 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001218 return new DefaultPort(device, number, isEnabled, description.type(),
1219 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001220 }
1221
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001222 /**
1223 * Returns a Port, merging description given from multiple Providers.
1224 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001225 * @param device device the port is on
1226 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001227 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001228 * @return Port instance
1229 */
1230 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001231 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001232
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001233 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001234 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001235 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001236 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001237 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001238 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001239 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1240 if (portDesc != null) {
1241 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001242 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001243 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001244 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001245 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001246 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001247 if (e.getKey().equals(primary)) {
1248 continue;
1249 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001250 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001251 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001252 // Currently assuming there will never be a key conflict between
1253 // providers
1254
1255 // annotation merging. not so efficient, should revisit later
1256 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1257 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001258 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1259 continue;
1260 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001261 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001262 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001263 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001264 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001265 }
1266 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001267 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001268 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001269 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001270 PortDescription current = portDesc.value();
1271 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001272 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001273 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001274 }
1275
1276 /**
1277 * @return primary ProviderID, or randomly chosen one if none exists
1278 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001279 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001280 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001281 ProviderId fallBackPrimary = null;
1282 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1283 if (!e.getKey().isAncillary()) {
1284 return e.getKey();
1285 } else if (fallBackPrimary == null) {
1286 // pick randomly as a fallback in case there is no primary
1287 fallBackPrimary = e.getKey();
1288 }
1289 }
1290 return fallBackPrimary;
1291 }
1292
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001293 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001294 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001295 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001296 return providerDescs.get(pid);
1297 }
1298
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001299 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001300 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001301 }
1302
Jonathan Hart7d656f42015-01-27 14:07:23 -08001303 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001304 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001305 }
Madan Jampani47c93732014-10-06 20:46:08 -07001306
Jonathan Hart7d656f42015-01-27 14:07:23 -08001307 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001308 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001309 }
1310
Palash Kala6c526062018-04-03 18:25:11 +09001311 private void notifyPeers(InternalDeviceStatusChangeEvent event) {
1312 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001313 }
1314
Jonathan Hart7d656f42015-01-27 14:07:23 -08001315 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001316 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001317 }
1318
Jonathan Hart7d656f42015-01-27 14:07:23 -08001319 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001320 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001321 }
1322
Jonathan Hart7d656f42015-01-27 14:07:23 -08001323 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001324 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1325 }
1326
1327 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1328 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001329 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001330 } catch (IOException e) {
1331 log.error("Failed to send" + event + " to " + recipient, e);
1332 }
1333 }
1334
Palash Kala6c526062018-04-03 18:25:11 +09001335 private void notifyPeer(NodeId recipient, InternalDeviceStatusChangeEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001336 try {
Palash Kala6c526062018-04-03 18:25:11 +09001337 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001338 } catch (IOException e) {
1339 log.error("Failed to send" + event + " to " + recipient, e);
1340 }
1341 }
1342
1343 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1344 try {
1345 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1346 } catch (IOException e) {
1347 log.error("Failed to send" + event + " to " + recipient, e);
1348 }
1349 }
1350
1351 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1352 try {
1353 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1354 } catch (IOException e) {
1355 log.error("Failed to send" + event + " to " + recipient, e);
1356 }
1357 }
1358
1359 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1360 try {
1361 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1362 } catch (IOException e) {
1363 log.error("Failed to send" + event + " to " + recipient, e);
1364 }
1365 }
1366
1367 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1368 final NodeId self = clusterService.getLocalNode().id();
1369
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001370 final int numDevices = deviceDescs.size();
1371 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1372 final int portsPerDevice = 8; // random factor to minimize reallocation
1373 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1374 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001375
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001376 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001377
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001378 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001379 synchronized (devDescs) {
1380
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001381 // send device offline timestamp
1382 Timestamp lOffline = this.offline.get(deviceId);
1383 if (lOffline != null) {
1384 adOffline.put(deviceId, lOffline);
1385 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001386
1387 for (Entry<ProviderId, DeviceDescriptions>
1388 prov : devDescs.entrySet()) {
1389
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001390 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001391 final ProviderId provId = prov.getKey();
1392 final DeviceDescriptions descs = prov.getValue();
1393
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001394 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001395 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001396
1397 for (Entry<PortNumber, Timestamped<PortDescription>>
1398 portDesc : descs.getPortDescs().entrySet()) {
1399
1400 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001401 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001402 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001403 }
1404 }
1405 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001406 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001407
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001408 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001409 }
1410
1411 /**
1412 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001413 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001414 * Notify sender about out-dated information using regular replication message.
1415 * Send back advertisement to sender if not in sync.
1416 *
1417 * @param advertisement to respond to
1418 */
1419 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
pierventree1f80102021-10-01 22:01:22 +02001420 /*
1421 * NOTE that when an instance rejoins the cluster, it will generate
1422 * device events and send to the local apps through the delegate. This
1423 * approach might be not the best if the apps are not enough robust or
1424 * if there is no proper coordination in the cluster. Also, note that
1425 * any ECMap will act on the same way during the bootstrap process
1426 */
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001427 final NodeId sender = advertisement.sender();
1428
1429 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1430 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1431 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1432
1433 // Fragments to request
1434 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1435 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1436
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001437 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001438 final DeviceId deviceId = de.getKey();
1439 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1440
1441 synchronized (lDevice) {
1442 // latestTimestamp across provider
1443 // Note: can be null initially
1444 Timestamp localLatest = offline.get(deviceId);
1445
1446 // handle device Ads
1447 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1448 final ProviderId provId = prov.getKey();
1449 final DeviceDescriptions lDeviceDescs = prov.getValue();
1450
1451 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1452
1453
1454 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1455 Timestamp advDevTimestamp = devAds.get(devFragId);
1456
Jonathan Hart403ea932015-02-20 16:23:00 -08001457 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1458 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001459 // remote does not have it or outdated, suggest
pierventree1f80102021-10-01 22:01:22 +02001460 log.trace("send to {} device update {} for {}", sender, lProvDevice, deviceId);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001461 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1462 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1463 // local is outdated, request
pierventree1f80102021-10-01 22:01:22 +02001464 log.trace("need update {} < {} for device {} from {}", lProvDevice.timestamp(),
1465 advDevTimestamp, deviceId, sender);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001466 reqDevices.add(devFragId);
1467 }
1468
1469 // handle port Ads
1470 for (Entry<PortNumber, Timestamped<PortDescription>>
1471 pe : lDeviceDescs.getPortDescs().entrySet()) {
1472
1473 final PortNumber num = pe.getKey();
1474 final Timestamped<PortDescription> lPort = pe.getValue();
1475
1476 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1477
1478 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001479 if (advPortTimestamp == null || lPort.isNewerThan(
1480 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001481 // remote does not have it or outdated, suggest
pierventree1f80102021-10-01 22:01:22 +02001482 log.trace("send to {} port update {} for {}/{}", sender, lPort, deviceId, num);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001483 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1484 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1485 // local is outdated, request
pierventree1f80102021-10-01 22:01:22 +02001486 log.trace("need update {} < {} for port {} from {}", lPort.timestamp(),
1487 advPortTimestamp, num, sender);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001488 reqPorts.add(portFragId);
1489 }
1490
1491 // remove port Ad already processed
1492 portAds.remove(portFragId);
1493 } // end local port loop
1494
1495 // remove device Ad already processed
1496 devAds.remove(devFragId);
1497
1498 // find latest and update
1499 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1500 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001501 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001502 localLatest = providerLatest;
1503 }
1504 } // end local provider loop
1505
1506 // checking if remote timestamp is more recent.
1507 Timestamp rOffline = offlineAds.get(deviceId);
jaegonkim73c21bd2018-01-13 10:52:02 +09001508 if (localLatest == null || (rOffline != null && rOffline.compareTo(localLatest) > 0)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001509 // remote offline timestamp suggests that the
1510 // device is off-line
pierventree1f80102021-10-01 22:01:22 +02001511 log.trace("remote offline timestamp from {} suggests that the device {} is off-line",
1512 sender, deviceId);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001513 markOfflineInternal(deviceId, rOffline);
1514 }
1515
1516 Timestamp lOffline = offline.get(deviceId);
1517 if (lOffline != null && rOffline == null) {
1518 // locally offline, but remote is online, suggest offline
pierventree1f80102021-10-01 22:01:22 +02001519 log.trace("suggest to {} sthat the device {} is off-line", sender, deviceId);
Palash Kala6c526062018-04-03 18:25:11 +09001520 notifyPeer(sender, new InternalDeviceStatusChangeEvent(deviceId, lOffline, false));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001521 }
1522
1523 // remove device offline Ad already processed
1524 offlineAds.remove(deviceId);
1525 } // end local device loop
1526 } // device lock
1527
1528 // If there is any Ads left, request them
1529 log.trace("Ads left {}, {}", devAds, portAds);
1530 reqDevices.addAll(devAds.keySet());
1531 reqPorts.addAll(portAds.keySet());
1532
1533 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1534 log.trace("Nothing to request to remote peer {}", sender);
1535 return;
1536 }
1537
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001538 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001539
1540 // 2-way Anti-Entropy for now
1541 try {
1542 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1543 } catch (IOException e) {
1544 log.error("Failed to send response advertisement to " + sender, e);
1545 }
1546
1547// Sketch of 3-way Anti-Entropy
1548// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1549// ClusterMessage message = new ClusterMessage(
1550// clusterService.getLocalNode().id(),
1551// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1552// SERIALIZER.encode(request));
1553//
1554// try {
1555// clusterCommunicator.unicast(message, advertisement.sender());
1556// } catch (IOException e) {
1557// log.error("Failed to send advertisement reply to "
1558// + advertisement.sender(), e);
1559// }
Madan Jampani47c93732014-10-06 20:46:08 -07001560 }
1561
Madan Jampani255a58b2014-10-09 12:08:20 -07001562 private void notifyDelegateIfNotNull(DeviceEvent event) {
1563 if (event != null) {
1564 notifyDelegate(event);
1565 }
1566 }
1567
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001568 private final class SendAdvertisementTask implements Runnable {
1569
1570 @Override
1571 public void run() {
1572 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001573 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001574 return;
1575 }
1576
1577 try {
1578 final NodeId self = clusterService.getLocalNode().id();
1579 Set<ControllerNode> nodes = clusterService.getNodes();
1580
1581 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1582 .transform(toNodeId())
1583 .toList();
1584
1585 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001586 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001587 return;
1588 }
1589
1590 NodeId peer;
1591 do {
1592 int idx = RandomUtils.nextInt(0, nodeIds.size());
1593 peer = nodeIds.get(idx);
1594 } while (peer.equals(self));
1595
1596 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1597
1598 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001599 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001600 return;
1601 }
1602
1603 try {
1604 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1605 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001606 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001607 return;
1608 }
1609 } catch (Exception e) {
1610 // catch all Exception to avoid Scheduled task being suppressed.
1611 log.error("Exception thrown while sending advertisement", e);
1612 }
1613 }
1614 }
1615
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001616 private void handleDeviceEvent(InternalDeviceEvent event) {
1617 ProviderId providerId = event.providerId();
1618 DeviceId deviceId = event.deviceId();
1619 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001620
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001621 try {
1622 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1623 deviceDescription));
1624 } catch (Exception e) {
1625 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001626 }
1627 }
1628
Palash Kala6c526062018-04-03 18:25:11 +09001629 private void handleDeviceStatusChangeEvent(InternalDeviceStatusChangeEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001630 DeviceId deviceId = event.deviceId();
1631 Timestamp timestamp = event.timestamp();
Palash Kala6c526062018-04-03 18:25:11 +09001632 Boolean available = event.available();
Madan Jampani25322532014-10-08 11:20:38 -07001633
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001634 try {
Palash Kala6c526062018-04-03 18:25:11 +09001635 if (available) {
1636 notifyDelegateIfNotNull(markOnlineInternal(deviceId, timestamp));
1637 } else {
1638 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1639 }
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001640 } catch (Exception e) {
Palash Kala6c526062018-04-03 18:25:11 +09001641 log.warn("Exception thrown handling device status change event", e);
Madan Jampani25322532014-10-08 11:20:38 -07001642 }
1643 }
1644
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001645 private void handleRemoveRequest(DeviceId did) {
1646 try {
Jayasree Ghosh7d96d6a2017-02-27 18:35:32 +05301647 DeviceEvent event = removeDevice(did);
1648 notifyDelegateIfNotNull(event);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001649 } catch (Exception e) {
1650 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001651 }
1652 }
1653
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001654 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1655 DeviceId deviceId = event.deviceId();
1656 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001657
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001658 try {
1659 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1660 } catch (Exception e) {
1661 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001662 }
1663 }
1664
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001665 private void handlePortEvent(InternalPortEvent event) {
1666 ProviderId providerId = event.providerId();
1667 DeviceId deviceId = event.deviceId();
1668 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001669
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001670 if (getDevice(deviceId) == null) {
1671 log.debug("{} not found on this node yet, ignoring.", deviceId);
1672 // Note: dropped information will be recovered by anti-entropy
1673 return;
1674 }
Madan Jampani47c93732014-10-06 20:46:08 -07001675
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001676 try {
1677 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1678 } catch (Exception e) {
1679 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001680 }
1681 }
1682
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001683 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1684 ProviderId providerId = event.providerId();
1685 DeviceId deviceId = event.deviceId();
1686 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001687
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001688 if (getDevice(deviceId) == null) {
1689 log.debug("{} not found on this node yet, ignoring.", deviceId);
1690 // Note: dropped information will be recovered by anti-entropy
1691 return;
1692 }
Madan Jampani47c93732014-10-06 20:46:08 -07001693
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001694 try {
1695 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1696 } catch (Exception e) {
1697 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001698 }
1699 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001700
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001701 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1702 try {
1703 handleAdvertisement(advertisement);
1704 } catch (Exception e) {
1705 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001706 }
1707 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001708
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001709 private class InternalPortStatsListener
1710 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1711 @Override
1712 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1713 if (event.type() == PUT) {
1714 Device device = devices.get(event.key());
1715 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001716 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001717 }
1718 }
1719 }
1720 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001721}