blob: 885d6b016969ce721b8625d296b758d3994ed938 [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) {
688 events.add(removePort(deviceId, oldPort.number()));
689 } 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
Michal Machce774332017-01-25 11:02:55 +0100727 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
728
729 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
730 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
731
732 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
733 }
734
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700735 // Prunes the specified list of ports based on which ports are in the
736 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700737 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700738 private List<DeviceEvent> pruneOldPorts(Device device,
739 Map<PortNumber, Port> ports,
740 Set<PortNumber> processed) {
741 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700742 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700743 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700744 Entry<PortNumber, Port> e = iterator.next();
745 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700746 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700747 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700748 iterator.remove();
749 }
750 }
751 return events;
752 }
753
754 // Gets the map of ports for the specified device; if one does not already
755 // exist, it creates and registers a new one.
756 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700757 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700758 }
759
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700760 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700761 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700762 Map<ProviderId, DeviceDescriptions> r;
763 r = deviceDescs.get(deviceId);
764 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700765 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700766 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
767 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
768 if (concurrentlyAdded != null) {
769 r = concurrentlyAdded;
770 }
771 }
772 return r;
773 }
774
775 // Guarded by deviceDescs value (=Device lock)
776 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
777 Map<ProviderId, DeviceDescriptions> device,
778 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700779 synchronized (device) {
780 DeviceDescriptions r = device.get(providerId);
781 if (r == null) {
782 r = new DeviceDescriptions(deltaDesc);
783 device.put(providerId, r);
784 }
785 return r;
786 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700787 }
788
789 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700790 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
791 DeviceId deviceId,
792 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700793 final Timestamp newTimestamp;
794 try {
795 newTimestamp = deviceClockService.getTimestamp(deviceId);
796 } catch (IllegalStateException e) {
797 log.info("Timestamp was not available for device {}", deviceId);
798 log.debug(" discarding {}", portDescription);
799 // Failed to generate timestamp. Ignoring.
800 // See updatePorts comment
801 return null;
802 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700803 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700804 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700805 final DeviceEvent event;
806 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800807 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
808 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700809 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800810 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700811 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700812 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700813 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700814 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700815 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800816 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700817 }
818 return event;
819 }
820
821 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700822 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700823 Device device = devices.get(deviceId);
824 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
825
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700826 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700827 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
828
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700829 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700830
831 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
832 log.debug("Ignoring outdated event: {}", deltaDesc);
833 return null;
834 }
835
836 DeviceDescriptions descs = descsMap.get(providerId);
837 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700838 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700839 "Device description for Device ID %s from Provider %s was not found",
840 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700841
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700842 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
843 final PortNumber number = deltaDesc.value().portNumber();
844 final Port oldPort = ports.get(number);
845 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700846 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100847 boolean toDelete = false;
848
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700849 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700850 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700851 // on new port or valid update
852 // update description
853 descs.putPortDesc(deltaDesc);
854 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100855 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700856 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700857 // same or outdated event, ignored.
858 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700859 return null;
860 }
861
862 if (oldPort == null) {
863 return createPort(device, newPort, ports);
864 } else {
Michal Machce774332017-01-25 11:02:55 +0100865 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700866 }
867 }
868 }
869
870 @Override
871 public List<Port> getPorts(DeviceId deviceId) {
872 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
873 if (ports == null) {
874 return Collections.emptyList();
875 }
876 return ImmutableList.copyOf(ports.values());
877 }
878
879 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700880 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
881 DeviceId deviceId) {
882 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
883 if (descs == null) {
Donghyeok Ho6de4fb92018-01-31 11:04:19 +0900884 return Stream.empty();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700885 }
886 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
887 final Optional<DeviceDescriptions> devDescs;
888 synchronized (descs) {
889 devDescs = Optional.ofNullable(descs.get(pid));
890 }
891 // DeviceDescriptions is concurrent access-safe
892 return devDescs
893 .map(dd -> dd.getPortDescs().values().stream()
894 .map(Timestamped::value))
895 .orElse(Stream.empty());
896 }
897
898 @Override
sangho538108b2015-04-08 14:29:20 -0700899 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200900 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700901
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200902 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
903 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
904 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
905
906 if (prvStatsMap != null) {
907 for (PortStatistics newStats : newStatsCollection) {
Ray Milkey5ec42082019-02-13 09:56:07 -0800908 PortNumber port = newStats.portNumber();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200909 PortStatistics prvStats = prvStatsMap.get(port);
910 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
911 PortStatistics deltaStats = builder.build();
912 if (prvStats != null) {
913 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
914 }
915 deltaStatsMap.put(port, deltaStats);
916 newStatsMap.put(port, newStats);
917 }
918 } else {
919 for (PortStatistics newStats : newStatsCollection) {
Ray Milkey5ec42082019-02-13 09:56:07 -0800920 PortNumber port = newStats.portNumber();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200921 newStatsMap.put(port, newStats);
922 }
sangho538108b2015-04-08 14:29:20 -0700923 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200924 devicePortDeltaStats.put(deviceId, deltaStatsMap);
925 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200926 // DeviceEvent returns null because of InternalPortStatsListener usage
927 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200928 }
929
930 /**
931 * Calculate delta statistics by subtracting previous from new statistics.
932 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700933 * @param deviceId device identifier
934 * @param prvStats previous port statistics
935 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200936 * @return PortStatistics
937 */
938 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
939 // calculate time difference
940 long deltaStatsSec, deltaStatsNano;
941 if (newStats.durationNano() < prvStats.durationNano()) {
942 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
943 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
944 } else {
945 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
946 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
947 }
948 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
949 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
Ray Milkey5ec42082019-02-13 09:56:07 -0800950 .setPort(newStats.portNumber())
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200951 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
952 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
953 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
954 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
955 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
956 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
957 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
958 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
959 .setDurationSec(deltaStatsSec)
960 .setDurationNano(deltaStatsNano)
961 .build();
962 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700963 }
964
965 @Override
966 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700967 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
968 if (portStats == null) {
969 return Collections.emptyList();
970 }
971 return ImmutableList.copyOf(portStats.values());
972 }
973
974 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530975 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
976 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
977 if (portStatsMap == null) {
978 return null;
979 }
980 PortStatistics portStats = portStatsMap.get(portNumber);
981 return portStats;
982 }
983
984 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200985 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
986 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
987 if (portStats == null) {
988 return Collections.emptyList();
989 }
990 return ImmutableList.copyOf(portStats.values());
991 }
992
993 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530994 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
995 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
996 if (portStatsMap == null) {
997 return null;
998 }
999 PortStatistics portStats = portStatsMap.get(portNumber);
1000 return portStats;
1001 }
1002
1003 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001004 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
1005 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1006 return ports == null ? null : ports.get(portNumber);
1007 }
1008
1009 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -07001010 public PortDescription getPortDescription(ProviderId pid,
1011 DeviceId deviceId,
1012 PortNumber portNumber) {
1013 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1014 if (descs == null) {
1015 return null;
1016 }
1017 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1018 final Optional<DeviceDescriptions> devDescs;
1019 synchronized (descs) {
1020 devDescs = Optional.ofNullable(descs.get(pid));
1021 }
1022 // DeviceDescriptions is concurrent access-safe
1023 return devDescs
1024 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1025 .map(Timestamped::value)
1026 .orElse(null);
1027 }
1028
1029 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001030 public boolean isAvailable(DeviceId deviceId) {
1031 return availableDevices.contains(deviceId);
1032 }
1033
1034 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001035 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001036 final NodeId myId = clusterService.getLocalNode().id();
1037 NodeId master = mastershipService.getMasterFor(deviceId);
1038
1039 // if there exist a master, forward
1040 // if there is no master, try to become one and process
1041
1042 boolean relinquishAtEnd = false;
1043 if (master == null) {
1044 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1045 if (myRole != MastershipRole.NONE) {
1046 relinquishAtEnd = true;
1047 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001048 log.debug("Temporarily requesting role for {} to remove", deviceId);
Jordan Haltermanf1c602d2017-10-18 11:26:52 -07001049 if (mastershipService.requestRoleFor(deviceId).join() == MastershipRole.MASTER) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001050 master = myId;
1051 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001052 }
1053
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001054 boolean isMaster = myId.equals(master);
1055
1056 // If this node is not the master, forward the request.
1057 if (!isMaster) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001058 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001059 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001060
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001061 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001062 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001063 /* error log:
1064 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1065 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001066 }
1067
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001068 // If this node is the master, get a timestamp. Otherwise, default to the current device timestamp.
1069 Timestamp timestamp = isMaster ? deviceClockService.getTimestamp(deviceId) : null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001070
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001071 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001072
1073 // If this node is the master, update peers.
1074 if (isMaster && event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001075 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001076 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001077 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001078 }
pier388ec252020-04-15 20:53:14 +02001079 notifyDelegateIfNotNull(event);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001080
1081 // Relinquish mastership if acquired to remove the device.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001082 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001083 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001084 mastershipService.relinquishMastership(deviceId);
1085 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001086 return event;
1087 }
1088
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001089 private DeviceEvent removeDeviceInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001090
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001091 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001092 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001093 // accept removal request if given timestamp is newer than
1094 // the latest Timestamp from Primary provider
1095 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001096 if (primDescs == null) {
1097 return null;
1098 }
1099
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001100 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001101
1102 // If no timestamp is set, default the timestamp to the last timestamp for the device.
1103 if (timestamp == null) {
1104 timestamp = lastTimestamp;
1105 }
1106
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001107 if (timestamp.compareTo(lastTimestamp) <= 0) {
1108 // outdated event ignore
1109 return null;
1110 }
1111 removalRequest.put(deviceId, timestamp);
1112
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001113 Device device = devices.remove(deviceId);
1114 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001115 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1116 if (ports != null) {
1117 ports.clear();
1118 }
1119 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001120 descs.clear();
pier388ec252020-04-15 20:53:14 +02001121 // Forget about the device
1122 offline.remove(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001123 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001124 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001125 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001126 }
1127
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001128 /**
1129 * Checks if given timestamp is superseded by removal request
1130 * with more recent timestamp.
1131 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001132 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001133 * @param timestampToCheck timestamp of an event to check
1134 * @return true if device is already removed
1135 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001136 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1137 Timestamp removalTimestamp = removalRequest.get(deviceId);
1138 if (removalTimestamp != null &&
Jordan Halterman8a0b3972017-08-15 16:14:18 -07001139 removalTimestamp.compareTo(timestampToCheck) > 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001140 // removalRequest is more recent
1141 return true;
1142 }
1143 return false;
1144 }
1145
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001146 /**
1147 * Returns a Device, merging description given from multiple Providers.
1148 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001149 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001150 * @param providerDescs Collection of Descriptions from multiple providers
1151 * @return Device instance
1152 */
1153 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001154 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001155
Thomas Vachuska444eda62014-10-28 13:09:42 -07001156 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001157
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001158 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001159
1160 DeviceDescriptions desc = providerDescs.get(primary);
1161
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001162 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001163 Type type = base.type();
1164 String manufacturer = base.manufacturer();
1165 String hwVersion = base.hwVersion();
1166 String swVersion = base.swVersion();
1167 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001168 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001169 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1170 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001171
1172 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1173 if (e.getKey().equals(primary)) {
1174 continue;
1175 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001176 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001177 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001178 // Currently assuming there will never be a key conflict between
1179 // providers
1180
1181 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001182 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001183 }
1184
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001185 return new DefaultDevice(primary, deviceId, type, manufacturer,
1186 hwVersion, swVersion, serialNumber,
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001187 chassisId, annotations.buildCompressed());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001188 }
1189
Marc De Leenheer88194c32015-05-29 22:10:59 -07001190 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1191 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001192 return new DefaultPort(device, number, isEnabled, description.type(),
1193 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001194 }
1195
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001196 /**
1197 * Returns a Port, merging description given from multiple Providers.
1198 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001199 * @param device device the port is on
1200 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001201 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001202 * @return Port instance
1203 */
1204 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001205 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001206
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001207 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001208 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001209 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001210 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001211 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001212 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001213 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1214 if (portDesc != null) {
1215 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001216 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001217 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001218 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001219 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001220 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001221 if (e.getKey().equals(primary)) {
1222 continue;
1223 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001224 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001225 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001226 // Currently assuming there will never be a key conflict between
1227 // providers
1228
1229 // annotation merging. not so efficient, should revisit later
1230 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1231 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001232 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1233 continue;
1234 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001235 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001236 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001237 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001238 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001239 }
1240 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001241 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001242 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001243 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001244 PortDescription current = portDesc.value();
1245 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001246 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001247 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001248 }
1249
1250 /**
1251 * @return primary ProviderID, or randomly chosen one if none exists
1252 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001253 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001254 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001255 ProviderId fallBackPrimary = null;
1256 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1257 if (!e.getKey().isAncillary()) {
1258 return e.getKey();
1259 } else if (fallBackPrimary == null) {
1260 // pick randomly as a fallback in case there is no primary
1261 fallBackPrimary = e.getKey();
1262 }
1263 }
1264 return fallBackPrimary;
1265 }
1266
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001267 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001268 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001269 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001270 return providerDescs.get(pid);
1271 }
1272
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001273 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001274 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001275 }
1276
Jonathan Hart7d656f42015-01-27 14:07:23 -08001277 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001278 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001279 }
Madan Jampani47c93732014-10-06 20:46:08 -07001280
Jonathan Hart7d656f42015-01-27 14:07:23 -08001281 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001282 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001283 }
1284
Palash Kala6c526062018-04-03 18:25:11 +09001285 private void notifyPeers(InternalDeviceStatusChangeEvent event) {
1286 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001287 }
1288
Jonathan Hart7d656f42015-01-27 14:07:23 -08001289 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001290 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001291 }
1292
Jonathan Hart7d656f42015-01-27 14:07:23 -08001293 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001294 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001295 }
1296
Jonathan Hart7d656f42015-01-27 14:07:23 -08001297 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001298 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1299 }
1300
1301 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1302 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001303 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001304 } catch (IOException e) {
1305 log.error("Failed to send" + event + " to " + recipient, e);
1306 }
1307 }
1308
Palash Kala6c526062018-04-03 18:25:11 +09001309 private void notifyPeer(NodeId recipient, InternalDeviceStatusChangeEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001310 try {
Palash Kala6c526062018-04-03 18:25:11 +09001311 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001312 } catch (IOException e) {
1313 log.error("Failed to send" + event + " to " + recipient, e);
1314 }
1315 }
1316
1317 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1318 try {
1319 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1320 } catch (IOException e) {
1321 log.error("Failed to send" + event + " to " + recipient, e);
1322 }
1323 }
1324
1325 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1326 try {
1327 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1328 } catch (IOException e) {
1329 log.error("Failed to send" + event + " to " + recipient, e);
1330 }
1331 }
1332
1333 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1334 try {
1335 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1336 } catch (IOException e) {
1337 log.error("Failed to send" + event + " to " + recipient, e);
1338 }
1339 }
1340
1341 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1342 final NodeId self = clusterService.getLocalNode().id();
1343
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001344 final int numDevices = deviceDescs.size();
1345 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1346 final int portsPerDevice = 8; // random factor to minimize reallocation
1347 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1348 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001349
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001350 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001351
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001352 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001353 synchronized (devDescs) {
1354
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001355 // send device offline timestamp
1356 Timestamp lOffline = this.offline.get(deviceId);
1357 if (lOffline != null) {
1358 adOffline.put(deviceId, lOffline);
1359 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001360
1361 for (Entry<ProviderId, DeviceDescriptions>
1362 prov : devDescs.entrySet()) {
1363
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001364 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001365 final ProviderId provId = prov.getKey();
1366 final DeviceDescriptions descs = prov.getValue();
1367
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001368 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001369 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001370
1371 for (Entry<PortNumber, Timestamped<PortDescription>>
1372 portDesc : descs.getPortDescs().entrySet()) {
1373
1374 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001375 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001376 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001377 }
1378 }
1379 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001380 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001381
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001382 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001383 }
1384
1385 /**
1386 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001387 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001388 * Notify sender about out-dated information using regular replication message.
1389 * Send back advertisement to sender if not in sync.
1390 *
1391 * @param advertisement to respond to
1392 */
1393 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1394
1395 final NodeId sender = advertisement.sender();
1396
1397 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1398 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1399 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1400
1401 // Fragments to request
1402 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1403 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1404
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001405 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001406 final DeviceId deviceId = de.getKey();
1407 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1408
1409 synchronized (lDevice) {
1410 // latestTimestamp across provider
1411 // Note: can be null initially
1412 Timestamp localLatest = offline.get(deviceId);
1413
1414 // handle device Ads
1415 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1416 final ProviderId provId = prov.getKey();
1417 final DeviceDescriptions lDeviceDescs = prov.getValue();
1418
1419 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1420
1421
1422 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1423 Timestamp advDevTimestamp = devAds.get(devFragId);
1424
Jonathan Hart403ea932015-02-20 16:23:00 -08001425 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1426 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001427 // remote does not have it or outdated, suggest
1428 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1429 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1430 // local is outdated, request
1431 reqDevices.add(devFragId);
1432 }
1433
1434 // handle port Ads
1435 for (Entry<PortNumber, Timestamped<PortDescription>>
1436 pe : lDeviceDescs.getPortDescs().entrySet()) {
1437
1438 final PortNumber num = pe.getKey();
1439 final Timestamped<PortDescription> lPort = pe.getValue();
1440
1441 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1442
1443 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001444 if (advPortTimestamp == null || lPort.isNewerThan(
1445 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001446 // remote does not have it or outdated, suggest
1447 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1448 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1449 // local is outdated, request
1450 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1451 reqPorts.add(portFragId);
1452 }
1453
1454 // remove port Ad already processed
1455 portAds.remove(portFragId);
1456 } // end local port loop
1457
1458 // remove device Ad already processed
1459 devAds.remove(devFragId);
1460
1461 // find latest and update
1462 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1463 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001464 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001465 localLatest = providerLatest;
1466 }
1467 } // end local provider loop
1468
1469 // checking if remote timestamp is more recent.
1470 Timestamp rOffline = offlineAds.get(deviceId);
jaegonkim73c21bd2018-01-13 10:52:02 +09001471 if (localLatest == null || (rOffline != null && rOffline.compareTo(localLatest) > 0)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001472 // remote offline timestamp suggests that the
1473 // device is off-line
1474 markOfflineInternal(deviceId, rOffline);
1475 }
1476
1477 Timestamp lOffline = offline.get(deviceId);
1478 if (lOffline != null && rOffline == null) {
1479 // locally offline, but remote is online, suggest offline
Palash Kala6c526062018-04-03 18:25:11 +09001480 notifyPeer(sender, new InternalDeviceStatusChangeEvent(deviceId, lOffline, false));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001481 }
1482
1483 // remove device offline Ad already processed
1484 offlineAds.remove(deviceId);
1485 } // end local device loop
1486 } // device lock
1487
1488 // If there is any Ads left, request them
1489 log.trace("Ads left {}, {}", devAds, portAds);
1490 reqDevices.addAll(devAds.keySet());
1491 reqPorts.addAll(portAds.keySet());
1492
1493 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1494 log.trace("Nothing to request to remote peer {}", sender);
1495 return;
1496 }
1497
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001498 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001499
1500 // 2-way Anti-Entropy for now
1501 try {
1502 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1503 } catch (IOException e) {
1504 log.error("Failed to send response advertisement to " + sender, e);
1505 }
1506
1507// Sketch of 3-way Anti-Entropy
1508// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1509// ClusterMessage message = new ClusterMessage(
1510// clusterService.getLocalNode().id(),
1511// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1512// SERIALIZER.encode(request));
1513//
1514// try {
1515// clusterCommunicator.unicast(message, advertisement.sender());
1516// } catch (IOException e) {
1517// log.error("Failed to send advertisement reply to "
1518// + advertisement.sender(), e);
1519// }
Madan Jampani47c93732014-10-06 20:46:08 -07001520 }
1521
Madan Jampani255a58b2014-10-09 12:08:20 -07001522 private void notifyDelegateIfNotNull(DeviceEvent event) {
1523 if (event != null) {
1524 notifyDelegate(event);
1525 }
1526 }
1527
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001528 private final class SendAdvertisementTask implements Runnable {
1529
1530 @Override
1531 public void run() {
1532 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001533 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001534 return;
1535 }
1536
1537 try {
1538 final NodeId self = clusterService.getLocalNode().id();
1539 Set<ControllerNode> nodes = clusterService.getNodes();
1540
1541 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1542 .transform(toNodeId())
1543 .toList();
1544
1545 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001546 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001547 return;
1548 }
1549
1550 NodeId peer;
1551 do {
1552 int idx = RandomUtils.nextInt(0, nodeIds.size());
1553 peer = nodeIds.get(idx);
1554 } while (peer.equals(self));
1555
1556 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1557
1558 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001559 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001560 return;
1561 }
1562
1563 try {
1564 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1565 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001566 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001567 return;
1568 }
1569 } catch (Exception e) {
1570 // catch all Exception to avoid Scheduled task being suppressed.
1571 log.error("Exception thrown while sending advertisement", e);
1572 }
1573 }
1574 }
1575
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001576 private void handleDeviceEvent(InternalDeviceEvent event) {
1577 ProviderId providerId = event.providerId();
1578 DeviceId deviceId = event.deviceId();
1579 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001580
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001581 try {
1582 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1583 deviceDescription));
1584 } catch (Exception e) {
1585 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001586 }
1587 }
1588
Palash Kala6c526062018-04-03 18:25:11 +09001589 private void handleDeviceStatusChangeEvent(InternalDeviceStatusChangeEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001590 DeviceId deviceId = event.deviceId();
1591 Timestamp timestamp = event.timestamp();
Palash Kala6c526062018-04-03 18:25:11 +09001592 Boolean available = event.available();
Madan Jampani25322532014-10-08 11:20:38 -07001593
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001594 try {
Palash Kala6c526062018-04-03 18:25:11 +09001595 if (available) {
1596 notifyDelegateIfNotNull(markOnlineInternal(deviceId, timestamp));
1597 } else {
1598 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1599 }
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001600 } catch (Exception e) {
Palash Kala6c526062018-04-03 18:25:11 +09001601 log.warn("Exception thrown handling device status change event", e);
Madan Jampani25322532014-10-08 11:20:38 -07001602 }
1603 }
1604
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001605 private void handleRemoveRequest(DeviceId did) {
1606 try {
Jayasree Ghosh7d96d6a2017-02-27 18:35:32 +05301607 DeviceEvent event = removeDevice(did);
1608 notifyDelegateIfNotNull(event);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001609 } catch (Exception e) {
1610 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001611 }
1612 }
1613
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001614 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1615 DeviceId deviceId = event.deviceId();
1616 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001617
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001618 try {
1619 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1620 } catch (Exception e) {
1621 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001622 }
1623 }
1624
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001625 private void handlePortEvent(InternalPortEvent event) {
1626 ProviderId providerId = event.providerId();
1627 DeviceId deviceId = event.deviceId();
1628 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001629
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001630 if (getDevice(deviceId) == null) {
1631 log.debug("{} not found on this node yet, ignoring.", deviceId);
1632 // Note: dropped information will be recovered by anti-entropy
1633 return;
1634 }
Madan Jampani47c93732014-10-06 20:46:08 -07001635
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001636 try {
1637 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1638 } catch (Exception e) {
1639 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001640 }
1641 }
1642
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001643 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1644 ProviderId providerId = event.providerId();
1645 DeviceId deviceId = event.deviceId();
1646 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001647
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001648 if (getDevice(deviceId) == null) {
1649 log.debug("{} not found on this node yet, ignoring.", deviceId);
1650 // Note: dropped information will be recovered by anti-entropy
1651 return;
1652 }
Madan Jampani47c93732014-10-06 20:46:08 -07001653
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001654 try {
1655 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1656 } catch (Exception e) {
1657 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001658 }
1659 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001660
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001661 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1662 try {
1663 handleAdvertisement(advertisement);
1664 } catch (Exception e) {
1665 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001666 }
1667 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001668
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001669 private class InternalPortStatsListener
1670 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1671 @Override
1672 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1673 if (event.type() == PUT) {
1674 Device device = devices.get(event.key());
1675 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001676 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001677 }
1678 }
1679 }
1680 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001681}