blob: 5760e235085415ab826a513f27e6b3b28125b31f [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
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001040 public boolean isAvailable(DeviceId deviceId) {
1041 return availableDevices.contains(deviceId);
1042 }
1043
1044 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001045 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001046 final NodeId myId = clusterService.getLocalNode().id();
1047 NodeId master = mastershipService.getMasterFor(deviceId);
1048
1049 // if there exist a master, forward
1050 // if there is no master, try to become one and process
1051
1052 boolean relinquishAtEnd = false;
1053 if (master == null) {
1054 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1055 if (myRole != MastershipRole.NONE) {
1056 relinquishAtEnd = true;
1057 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001058 log.debug("Temporarily requesting role for {} to remove", deviceId);
Jordan Haltermanf1c602d2017-10-18 11:26:52 -07001059 if (mastershipService.requestRoleFor(deviceId).join() == MastershipRole.MASTER) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001060 master = myId;
1061 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001062 }
1063
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001064 boolean isMaster = myId.equals(master);
1065
1066 // If this node is not the master, forward the request.
1067 if (!isMaster) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001068 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001069 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001070
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001071 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001072 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001073 /* error log:
1074 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1075 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001076 }
1077
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001078 // If this node is the master, get a timestamp. Otherwise, default to the current device timestamp.
1079 Timestamp timestamp = isMaster ? deviceClockService.getTimestamp(deviceId) : null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001080
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001081 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001082
1083 // If this node is the master, update peers.
1084 if (isMaster && event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001085 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001086 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001087 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001088 }
pier388ec252020-04-15 20:53:14 +02001089 notifyDelegateIfNotNull(event);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001090
1091 // Relinquish mastership if acquired to remove the device.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001092 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001093 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001094 mastershipService.relinquishMastership(deviceId);
1095 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001096 return event;
1097 }
1098
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001099 private DeviceEvent removeDeviceInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001100
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001101 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001102 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001103 // accept removal request if given timestamp is newer than
1104 // the latest Timestamp from Primary provider
1105 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001106 if (primDescs == null) {
1107 return null;
1108 }
1109
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001110 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001111
1112 // If no timestamp is set, default the timestamp to the last timestamp for the device.
1113 if (timestamp == null) {
1114 timestamp = lastTimestamp;
1115 }
1116
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001117 if (timestamp.compareTo(lastTimestamp) <= 0) {
1118 // outdated event ignore
1119 return null;
1120 }
1121 removalRequest.put(deviceId, timestamp);
1122
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001123 Device device = devices.remove(deviceId);
Andrea Campanellab0dfbc82020-08-10 18:06:42 +02001124 //removing internal description
1125 deviceDescs.remove(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001126 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001127 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1128 if (ports != null) {
1129 ports.clear();
1130 }
1131 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001132 descs.clear();
pier388ec252020-04-15 20:53:14 +02001133 // Forget about the device
1134 offline.remove(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001135 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001136 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001137 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001138 }
1139
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001140 /**
1141 * Checks if given timestamp is superseded by removal request
1142 * with more recent timestamp.
1143 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001144 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001145 * @param timestampToCheck timestamp of an event to check
1146 * @return true if device is already removed
1147 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001148 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1149 Timestamp removalTimestamp = removalRequest.get(deviceId);
1150 if (removalTimestamp != null &&
Jordan Halterman8a0b3972017-08-15 16:14:18 -07001151 removalTimestamp.compareTo(timestampToCheck) > 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001152 // removalRequest is more recent
1153 return true;
1154 }
1155 return false;
1156 }
1157
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001158 /**
1159 * Returns a Device, merging description given from multiple Providers.
1160 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001161 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001162 * @param providerDescs Collection of Descriptions from multiple providers
1163 * @return Device instance
1164 */
1165 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001166 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001167
Thomas Vachuska444eda62014-10-28 13:09:42 -07001168 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001169
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001170 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001171
1172 DeviceDescriptions desc = providerDescs.get(primary);
1173
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001174 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001175 Type type = base.type();
1176 String manufacturer = base.manufacturer();
1177 String hwVersion = base.hwVersion();
1178 String swVersion = base.swVersion();
1179 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001180 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001181 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1182 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001183
1184 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1185 if (e.getKey().equals(primary)) {
1186 continue;
1187 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001188 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001189 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001190 // Currently assuming there will never be a key conflict between
1191 // providers
1192
1193 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001194 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001195 }
1196
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001197 return new DefaultDevice(primary, deviceId, type, manufacturer,
1198 hwVersion, swVersion, serialNumber,
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001199 chassisId, annotations.buildCompressed());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001200 }
1201
Marc De Leenheer88194c32015-05-29 22:10:59 -07001202 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1203 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001204 return new DefaultPort(device, number, isEnabled, description.type(),
1205 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001206 }
1207
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001208 /**
1209 * Returns a Port, merging description given from multiple Providers.
1210 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001211 * @param device device the port is on
1212 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001213 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001214 * @return Port instance
1215 */
1216 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001217 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001218
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001219 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001220 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001221 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001222 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001223 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001224 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001225 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1226 if (portDesc != null) {
1227 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001228 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001229 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001230 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001231 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001232 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001233 if (e.getKey().equals(primary)) {
1234 continue;
1235 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001236 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001237 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001238 // Currently assuming there will never be a key conflict between
1239 // providers
1240
1241 // annotation merging. not so efficient, should revisit later
1242 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1243 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001244 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1245 continue;
1246 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001247 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001248 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001249 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001250 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001251 }
1252 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001253 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001254 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001255 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001256 PortDescription current = portDesc.value();
1257 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001258 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001259 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001260 }
1261
1262 /**
1263 * @return primary ProviderID, or randomly chosen one if none exists
1264 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001265 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001266 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001267 ProviderId fallBackPrimary = null;
1268 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1269 if (!e.getKey().isAncillary()) {
1270 return e.getKey();
1271 } else if (fallBackPrimary == null) {
1272 // pick randomly as a fallback in case there is no primary
1273 fallBackPrimary = e.getKey();
1274 }
1275 }
1276 return fallBackPrimary;
1277 }
1278
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001279 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001280 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001281 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001282 return providerDescs.get(pid);
1283 }
1284
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001285 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001286 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001287 }
1288
Jonathan Hart7d656f42015-01-27 14:07:23 -08001289 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001290 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001291 }
Madan Jampani47c93732014-10-06 20:46:08 -07001292
Jonathan Hart7d656f42015-01-27 14:07:23 -08001293 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001294 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001295 }
1296
Palash Kala6c526062018-04-03 18:25:11 +09001297 private void notifyPeers(InternalDeviceStatusChangeEvent event) {
1298 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001299 }
1300
Jonathan Hart7d656f42015-01-27 14:07:23 -08001301 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001302 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001303 }
1304
Jonathan Hart7d656f42015-01-27 14:07:23 -08001305 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001306 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001307 }
1308
Jonathan Hart7d656f42015-01-27 14:07:23 -08001309 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001310 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1311 }
1312
1313 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1314 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001315 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001316 } catch (IOException e) {
1317 log.error("Failed to send" + event + " to " + recipient, e);
1318 }
1319 }
1320
Palash Kala6c526062018-04-03 18:25:11 +09001321 private void notifyPeer(NodeId recipient, InternalDeviceStatusChangeEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001322 try {
Palash Kala6c526062018-04-03 18:25:11 +09001323 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001324 } catch (IOException e) {
1325 log.error("Failed to send" + event + " to " + recipient, e);
1326 }
1327 }
1328
1329 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1330 try {
1331 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1332 } catch (IOException e) {
1333 log.error("Failed to send" + event + " to " + recipient, e);
1334 }
1335 }
1336
1337 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1338 try {
1339 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1340 } catch (IOException e) {
1341 log.error("Failed to send" + event + " to " + recipient, e);
1342 }
1343 }
1344
1345 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1346 try {
1347 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1348 } catch (IOException e) {
1349 log.error("Failed to send" + event + " to " + recipient, e);
1350 }
1351 }
1352
1353 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1354 final NodeId self = clusterService.getLocalNode().id();
1355
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001356 final int numDevices = deviceDescs.size();
1357 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1358 final int portsPerDevice = 8; // random factor to minimize reallocation
1359 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1360 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001361
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001362 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001363
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001364 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001365 synchronized (devDescs) {
1366
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001367 // send device offline timestamp
1368 Timestamp lOffline = this.offline.get(deviceId);
1369 if (lOffline != null) {
1370 adOffline.put(deviceId, lOffline);
1371 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001372
1373 for (Entry<ProviderId, DeviceDescriptions>
1374 prov : devDescs.entrySet()) {
1375
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001376 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001377 final ProviderId provId = prov.getKey();
1378 final DeviceDescriptions descs = prov.getValue();
1379
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001380 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001381 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001382
1383 for (Entry<PortNumber, Timestamped<PortDescription>>
1384 portDesc : descs.getPortDescs().entrySet()) {
1385
1386 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001387 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001388 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001389 }
1390 }
1391 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001392 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001393
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001394 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001395 }
1396
1397 /**
1398 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001399 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001400 * Notify sender about out-dated information using regular replication message.
1401 * Send back advertisement to sender if not in sync.
1402 *
1403 * @param advertisement to respond to
1404 */
1405 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1406
1407 final NodeId sender = advertisement.sender();
1408
1409 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1410 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1411 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1412
1413 // Fragments to request
1414 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1415 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1416
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001417 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001418 final DeviceId deviceId = de.getKey();
1419 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1420
1421 synchronized (lDevice) {
1422 // latestTimestamp across provider
1423 // Note: can be null initially
1424 Timestamp localLatest = offline.get(deviceId);
1425
1426 // handle device Ads
1427 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1428 final ProviderId provId = prov.getKey();
1429 final DeviceDescriptions lDeviceDescs = prov.getValue();
1430
1431 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1432
1433
1434 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1435 Timestamp advDevTimestamp = devAds.get(devFragId);
1436
Jonathan Hart403ea932015-02-20 16:23:00 -08001437 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1438 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001439 // remote does not have it or outdated, suggest
1440 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1441 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1442 // local is outdated, request
1443 reqDevices.add(devFragId);
1444 }
1445
1446 // handle port Ads
1447 for (Entry<PortNumber, Timestamped<PortDescription>>
1448 pe : lDeviceDescs.getPortDescs().entrySet()) {
1449
1450 final PortNumber num = pe.getKey();
1451 final Timestamped<PortDescription> lPort = pe.getValue();
1452
1453 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1454
1455 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001456 if (advPortTimestamp == null || lPort.isNewerThan(
1457 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001458 // remote does not have it or outdated, suggest
1459 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1460 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1461 // local is outdated, request
1462 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1463 reqPorts.add(portFragId);
1464 }
1465
1466 // remove port Ad already processed
1467 portAds.remove(portFragId);
1468 } // end local port loop
1469
1470 // remove device Ad already processed
1471 devAds.remove(devFragId);
1472
1473 // find latest and update
1474 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1475 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001476 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001477 localLatest = providerLatest;
1478 }
1479 } // end local provider loop
1480
1481 // checking if remote timestamp is more recent.
1482 Timestamp rOffline = offlineAds.get(deviceId);
jaegonkim73c21bd2018-01-13 10:52:02 +09001483 if (localLatest == null || (rOffline != null && rOffline.compareTo(localLatest) > 0)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001484 // remote offline timestamp suggests that the
1485 // device is off-line
1486 markOfflineInternal(deviceId, rOffline);
1487 }
1488
1489 Timestamp lOffline = offline.get(deviceId);
1490 if (lOffline != null && rOffline == null) {
1491 // locally offline, but remote is online, suggest offline
Palash Kala6c526062018-04-03 18:25:11 +09001492 notifyPeer(sender, new InternalDeviceStatusChangeEvent(deviceId, lOffline, false));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001493 }
1494
1495 // remove device offline Ad already processed
1496 offlineAds.remove(deviceId);
1497 } // end local device loop
1498 } // device lock
1499
1500 // If there is any Ads left, request them
1501 log.trace("Ads left {}, {}", devAds, portAds);
1502 reqDevices.addAll(devAds.keySet());
1503 reqPorts.addAll(portAds.keySet());
1504
1505 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1506 log.trace("Nothing to request to remote peer {}", sender);
1507 return;
1508 }
1509
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001510 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001511
1512 // 2-way Anti-Entropy for now
1513 try {
1514 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1515 } catch (IOException e) {
1516 log.error("Failed to send response advertisement to " + sender, e);
1517 }
1518
1519// Sketch of 3-way Anti-Entropy
1520// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1521// ClusterMessage message = new ClusterMessage(
1522// clusterService.getLocalNode().id(),
1523// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1524// SERIALIZER.encode(request));
1525//
1526// try {
1527// clusterCommunicator.unicast(message, advertisement.sender());
1528// } catch (IOException e) {
1529// log.error("Failed to send advertisement reply to "
1530// + advertisement.sender(), e);
1531// }
Madan Jampani47c93732014-10-06 20:46:08 -07001532 }
1533
Madan Jampani255a58b2014-10-09 12:08:20 -07001534 private void notifyDelegateIfNotNull(DeviceEvent event) {
1535 if (event != null) {
1536 notifyDelegate(event);
1537 }
1538 }
1539
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001540 private final class SendAdvertisementTask implements Runnable {
1541
1542 @Override
1543 public void run() {
1544 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001545 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001546 return;
1547 }
1548
1549 try {
1550 final NodeId self = clusterService.getLocalNode().id();
1551 Set<ControllerNode> nodes = clusterService.getNodes();
1552
1553 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1554 .transform(toNodeId())
1555 .toList();
1556
1557 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001558 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001559 return;
1560 }
1561
1562 NodeId peer;
1563 do {
1564 int idx = RandomUtils.nextInt(0, nodeIds.size());
1565 peer = nodeIds.get(idx);
1566 } while (peer.equals(self));
1567
1568 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1569
1570 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001571 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001572 return;
1573 }
1574
1575 try {
1576 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1577 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001578 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001579 return;
1580 }
1581 } catch (Exception e) {
1582 // catch all Exception to avoid Scheduled task being suppressed.
1583 log.error("Exception thrown while sending advertisement", e);
1584 }
1585 }
1586 }
1587
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001588 private void handleDeviceEvent(InternalDeviceEvent event) {
1589 ProviderId providerId = event.providerId();
1590 DeviceId deviceId = event.deviceId();
1591 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001592
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001593 try {
1594 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1595 deviceDescription));
1596 } catch (Exception e) {
1597 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001598 }
1599 }
1600
Palash Kala6c526062018-04-03 18:25:11 +09001601 private void handleDeviceStatusChangeEvent(InternalDeviceStatusChangeEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001602 DeviceId deviceId = event.deviceId();
1603 Timestamp timestamp = event.timestamp();
Palash Kala6c526062018-04-03 18:25:11 +09001604 Boolean available = event.available();
Madan Jampani25322532014-10-08 11:20:38 -07001605
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001606 try {
Palash Kala6c526062018-04-03 18:25:11 +09001607 if (available) {
1608 notifyDelegateIfNotNull(markOnlineInternal(deviceId, timestamp));
1609 } else {
1610 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1611 }
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001612 } catch (Exception e) {
Palash Kala6c526062018-04-03 18:25:11 +09001613 log.warn("Exception thrown handling device status change event", e);
Madan Jampani25322532014-10-08 11:20:38 -07001614 }
1615 }
1616
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001617 private void handleRemoveRequest(DeviceId did) {
1618 try {
Jayasree Ghosh7d96d6a2017-02-27 18:35:32 +05301619 DeviceEvent event = removeDevice(did);
1620 notifyDelegateIfNotNull(event);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001621 } catch (Exception e) {
1622 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001623 }
1624 }
1625
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001626 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1627 DeviceId deviceId = event.deviceId();
1628 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001629
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001630 try {
1631 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1632 } catch (Exception e) {
1633 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001634 }
1635 }
1636
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001637 private void handlePortEvent(InternalPortEvent event) {
1638 ProviderId providerId = event.providerId();
1639 DeviceId deviceId = event.deviceId();
1640 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001641
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001642 if (getDevice(deviceId) == null) {
1643 log.debug("{} not found on this node yet, ignoring.", deviceId);
1644 // Note: dropped information will be recovered by anti-entropy
1645 return;
1646 }
Madan Jampani47c93732014-10-06 20:46:08 -07001647
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001648 try {
1649 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1650 } catch (Exception e) {
1651 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001652 }
1653 }
1654
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001655 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1656 ProviderId providerId = event.providerId();
1657 DeviceId deviceId = event.deviceId();
1658 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001659
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001660 if (getDevice(deviceId) == null) {
1661 log.debug("{} not found on this node yet, ignoring.", deviceId);
1662 // Note: dropped information will be recovered by anti-entropy
1663 return;
1664 }
Madan Jampani47c93732014-10-06 20:46:08 -07001665
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001666 try {
1667 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1668 } catch (Exception e) {
1669 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001670 }
1671 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001672
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001673 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1674 try {
1675 handleAdvertisement(advertisement);
1676 } catch (Exception e) {
1677 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001678 }
1679 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001680
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001681 private class InternalPortStatsListener
1682 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1683 @Override
1684 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1685 if (event.type() == PUT) {
1686 Device device = devices.get(event.key());
1687 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001688 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001689 }
1690 }
1691 }
1692 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001693}