blob: 32a9be61fe20c09a03e5c847bc982e5b5753b60a [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
Thomas Vachuskaa651de12018-04-19 12:11:09 -0700333 // FIXME: This may result in duplicate events as each instance reports on the new device
334 // regardless of whether it is a master or not.
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));
Andrea Campanellabba1e882018-05-14 18:17:28 +0200338 notifyDelegateIfNotNull(deviceEvent);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800339
340 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700341 }
342
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700343 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700344 DeviceId deviceId,
345 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700346
347 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800348 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700349 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700350
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800351 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700352 // locking per device
353
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700354 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
355 log.debug("Ignoring outdated event: {}", deltaDesc);
356 return null;
357 }
358
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800359 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700360
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700361 final Device oldDevice = devices.get(deviceId);
362 final Device newDevice;
363
364 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700365 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700366 // on new device or valid update
367 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800368 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700369 } else {
370 // outdated event, ignored.
371 return null;
372 }
Thomas Vachuskaf131e592018-05-07 11:52:14 -0700373
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700374 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700375 // REGISTER
376 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700377 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700378 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700379 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700380 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700381 } else {
382 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700383 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
384 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700385 }
386 }
387 }
388
389 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700390 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700391 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700392 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700393
394 // update composed device cache
395 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
396 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700397 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
398 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700399
400 if (!providerId.isAncillary()) {
Palash Kala6c526062018-04-03 18:25:11 +0900401 markOnline(newDevice.id(), timestamp, false);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700402 }
403
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700404 log.debug("Device {} added", newDevice.id());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700405 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
406 }
407
408 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700409 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700410 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700411 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700412 Device newDevice, Timestamp newTimestamp,
413 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700414 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700415 boolean propertiesChanged =
416 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700417 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
mskala4b2081a2017-06-12 16:39:50 +0200418 !Objects.equals(oldDevice.providerId(), newDevice.providerId()) ||
419 !Objects.equals(oldDevice.chassisId(), newDevice.chassisId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700420 boolean annotationsChanged =
421 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700422
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700423 // Primary providers can respond to all changes, but ancillary ones
424 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800425 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700426 if ((providerId.isAncillary() && annotationsChanged) ||
427 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700428 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
429 if (!replaced) {
430 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700431 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800432 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700433 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700434
Jordan Haltermanebedbb52017-08-08 15:57:50 -0700435 log.debug("Device {} updated", newDevice.id());
alshabibdc5d8bd2015-11-02 15:41:29 -0800436 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700437 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800438
helenyrwufd296b62016-06-22 17:43:02 -0700439 if (!providerId.isAncillary() && forceAvailable) {
Palash Kala6c526062018-04-03 18:25:11 +0900440 notifyDelegateIfNotNull(markOnline(newDevice.id(), newTimestamp, false));
alshabibdc5d8bd2015-11-02 15:41:29 -0800441 }
442 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700443 }
444
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700445 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700446 // update composed device cache
447 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
448 verify(oldDevice == null,
449 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
450 providerId, oldDevice, newDevice);
451
452 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700453 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700454 }
455
456 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
457 }
458
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700459 @Override
460 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700461 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
462 }
463
464 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700465 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700466 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700467 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700468 deviceId, timestamp);
Palash Kala6c526062018-04-03 18:25:11 +0900469 notifyPeers(new InternalDeviceStatusChangeEvent(deviceId, timestamp, false));
Madan Jampani25322532014-10-08 11:20:38 -0700470 }
471 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700472 }
473
474 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700475 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700476 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700477
478 // locking device
479 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700480 // accept off-line if given timestamp is newer than
481 // the latest Timestamp from Primary provider
482 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
jaegonkim73c21bd2018-01-13 10:52:02 +0900483 if (primDescs != null) {
484 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
485 if (lastTimestamp == null) {
486 lastTimestamp = deviceClockService.getTimestamp(deviceId);
487 }
488 if (timestamp.compareTo(lastTimestamp) <= 0) {
489 // outdated event ignore
490 return null;
491 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700492 }
493
494 offline.put(deviceId, timestamp);
495
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700496 Device device = devices.get(deviceId);
497 if (device == null) {
Andrea Campanellabba1e882018-05-14 18:17:28 +0200498 // Single Instance ONOS, device is removed from devices map and is null here but
499 // must still be marked offline
500 availableDevices.remove(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700501 return null;
502 }
503 boolean removed = availableDevices.remove(deviceId);
504 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700505 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700506 }
507 return null;
508 }
509 }
510
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700511 @Override
Palash Kala6c526062018-04-03 18:25:11 +0900512 public DeviceEvent markOnline(DeviceId deviceId) {
513 return markOnline(deviceId, deviceClockService.getTimestamp(deviceId), true);
helenyrwufd296b62016-06-22 17:43:02 -0700514 }
515
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700516 /**
517 * Marks the device as available if the given timestamp is not outdated,
518 * compared to the time the device has been marked offline.
519 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700520 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700521 * @param timestamp of the event triggering this change.
Palash Kala6c526062018-04-03 18:25:11 +0900522 * @param notifyPeers if the event needs to be notified to peers.
523 * @return ready to send event describing what occurred; null if no change
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700524 */
Palash Kala6c526062018-04-03 18:25:11 +0900525 private DeviceEvent markOnline(DeviceId deviceId, Timestamp timestamp, boolean notifyPeers) {
526 final DeviceEvent event = markOnlineInternal(deviceId, timestamp);
527 if (event != null && notifyPeers) {
528 log.debug("Notifying peers of a device online topology event for deviceId: {} {}",
529 deviceId, timestamp);
530 notifyPeers(new InternalDeviceStatusChangeEvent(deviceId, timestamp, true));
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700531 }
Palash Kala6c526062018-04-03 18:25:11 +0900532 return event;
533 }
534
535 // Guarded by deviceDescs value (=Device lock)
536 private DeviceEvent markOnlineInternal(DeviceId deviceId, Timestamp timestamp) {
537 if (devices.containsKey(deviceId)) {
538 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
539 synchronized (deviceLock) {
540 // accept on-line if given timestamp is newer than
541 // the latest offline request Timestamp
542 Timestamp offlineTimestamp = offline.get(deviceId);
543 if (offlineTimestamp == null ||
544 offlineTimestamp.compareTo(timestamp) < 0) {
545 offline.remove(deviceId);
546 Device device = devices.get(deviceId);
547 boolean add = availableDevices.add(deviceId);
548 if (add) {
549 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
550 }
551 }
552 }
Thomas Vachuskae36a2822018-05-03 12:16:52 -0700553 } else {
554 log.warn("Device {} does not exist in store", deviceId);
Palash Kala6c526062018-04-03 18:25:11 +0900555 }
Palash Kala6c526062018-04-03 18:25:11 +0900556 return null;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700557 }
558
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700559 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700560 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700561 DeviceId deviceId,
562 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700563
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800564 NodeId localNode = clusterService.getLocalNode().id();
565 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
566 // since it will trigger distributed store read.
567 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
568 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
569 // If we don't care much about topology performance, then it might be OK.
570 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700571
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800572 // Process port update only if we're the master of the device,
573 // otherwise signal the actual master.
574 List<DeviceEvent> deviceEvents = null;
575 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700576
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800577 final Timestamp newTimestamp;
578 try {
579 newTimestamp = deviceClockService.getTimestamp(deviceId);
580 } catch (IllegalStateException e) {
581 log.info("Timestamp was not available for device {}", deviceId);
582 log.debug(" discarding {}", portDescriptions);
583 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700584
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800585 // Possible situation:
586 // Device connected and became master for short period of time,
587 // but lost mastership before this instance had the chance to
588 // retrieve term information.
589
590 // Information dropped here is expected to be recoverable by
591 // device probing after mastership change
592
593 return Collections.emptyList();
594 }
595 log.debug("timestamp for {} {}", deviceId, newTimestamp);
596
597 final Timestamped<List<PortDescription>> timestampedInput
598 = new Timestamped<>(portDescriptions, newTimestamp);
599 final Timestamped<List<PortDescription>> merged;
600
601 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
602
603 synchronized (device) {
604 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
605 final DeviceDescriptions descs = device.get(providerId);
606 List<PortDescription> mergedList =
607 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700608 .transform(input ->
609 // lookup merged port description
610 descs.getPortDesc(input.portNumber()).value()
611 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700612 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800613 }
614
615 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700616 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700617 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800618 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
619 }
620
621 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700622 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700623 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700624
Ray Milkeyfe0e0852018-01-18 11:14:05 -0800625 return deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700626 }
627
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700628 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700629 DeviceId deviceId,
630 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700631
632 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700633 if (device == null) {
634 log.debug("Device is no longer valid: {}", deviceId);
635 return Collections.emptyList();
636 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700637
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700638 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700639 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
640
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700641 List<DeviceEvent> events = new ArrayList<>();
642 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700643
644 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
645 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700646 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700647 }
648
649 DeviceDescriptions descs = descsMap.get(providerId);
650 // every provider must provide DeviceDescription.
651 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700652 "Device description for Device ID %s from Provider %s was not found",
653 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700654
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700655 Map<PortNumber, Port> ports = getPortMap(deviceId);
656
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700657 final Timestamp newTimestamp = portDescriptions.timestamp();
658
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700659 // Add new ports
660 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700661 for (PortDescription portDescription : portDescriptions.value()) {
662 final PortNumber number = portDescription.portNumber();
663 processed.add(number);
664
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700665 final Port oldPort = ports.get(number);
666 final Port newPort;
Palash Kala8d30b612018-03-02 11:06:10 +0900667 boolean isRemoved = portDescription.isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700668
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700669
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700670 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
671 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700672 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700673 // on new port or valid update
674 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700675 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700676 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700677 newPort = composePort(device, number, descsMap);
678 } else {
679 // outdated event, ignored.
680 continue;
681 }
682
Palash Kala8d30b612018-03-02 11:06:10 +0900683 if (isRemoved && oldPort != null) {
684 events.add(removePort(deviceId, oldPort.number()));
685 } else if (!isRemoved) {
686 events.add(oldPort == null ?
687 createPort(device, newPort, ports) :
688 updatePort(device, oldPort, newPort, ports));
689 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700690 }
691
692 events.addAll(pruneOldPorts(device, ports, processed));
693 }
694 return FluentIterable.from(events).filter(notNull()).toList();
695 }
696
697 // Creates a new port based on the port description adds it to the map and
698 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700699 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700700 private DeviceEvent createPort(Device device, Port newPort,
701 Map<PortNumber, Port> ports) {
702 ports.put(newPort.number(), newPort);
703 return new DeviceEvent(PORT_ADDED, device, newPort);
704 }
705
706 // Checks if the specified port requires update and if so, it replaces the
707 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700708 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700709 private DeviceEvent updatePort(Device device, Port oldPort,
710 Port newPort,
711 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100712
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700713 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700714 oldPort.type() != newPort.type() ||
715 oldPort.portSpeed() != newPort.portSpeed() ||
716 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700717 ports.put(oldPort.number(), newPort);
718 return new DeviceEvent(PORT_UPDATED, device, newPort);
719 }
720 return null;
721 }
722
Michal Machce774332017-01-25 11:02:55 +0100723 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
724
725 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
726 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
727
728 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
729 }
730
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700731 // Prunes the specified list of ports based on which ports are in the
732 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700733 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700734 private List<DeviceEvent> pruneOldPorts(Device device,
735 Map<PortNumber, Port> ports,
736 Set<PortNumber> processed) {
737 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700738 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700739 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700740 Entry<PortNumber, Port> e = iterator.next();
741 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700742 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700743 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700744 iterator.remove();
745 }
746 }
747 return events;
748 }
749
750 // Gets the map of ports for the specified device; if one does not already
751 // exist, it creates and registers a new one.
752 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700753 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700754 }
755
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700756 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700757 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700758 Map<ProviderId, DeviceDescriptions> r;
759 r = deviceDescs.get(deviceId);
760 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700761 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700762 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
763 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
764 if (concurrentlyAdded != null) {
765 r = concurrentlyAdded;
766 }
767 }
768 return r;
769 }
770
771 // Guarded by deviceDescs value (=Device lock)
772 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
773 Map<ProviderId, DeviceDescriptions> device,
774 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700775 synchronized (device) {
776 DeviceDescriptions r = device.get(providerId);
777 if (r == null) {
778 r = new DeviceDescriptions(deltaDesc);
779 device.put(providerId, r);
780 }
781 return r;
782 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700783 }
784
785 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700786 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
787 DeviceId deviceId,
788 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700789 final Timestamp newTimestamp;
790 try {
791 newTimestamp = deviceClockService.getTimestamp(deviceId);
792 } catch (IllegalStateException e) {
793 log.info("Timestamp was not available for device {}", deviceId);
794 log.debug(" discarding {}", portDescription);
795 // Failed to generate timestamp. Ignoring.
796 // See updatePorts comment
797 return null;
798 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700799 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700800 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700801 final DeviceEvent event;
802 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800803 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
804 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700805 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800806 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700807 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700808 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700809 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700810 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700811 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800812 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700813 }
814 return event;
815 }
816
817 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700818 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700819 Device device = devices.get(deviceId);
820 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
821
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700822 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700823 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
824
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700825 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700826
827 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
828 log.debug("Ignoring outdated event: {}", deltaDesc);
829 return null;
830 }
831
832 DeviceDescriptions descs = descsMap.get(providerId);
833 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700834 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700835 "Device description for Device ID %s from Provider %s was not found",
836 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700837
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700838 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
839 final PortNumber number = deltaDesc.value().portNumber();
840 final Port oldPort = ports.get(number);
841 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700842 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100843 boolean toDelete = false;
844
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700845 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700846 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700847 // on new port or valid update
848 // update description
849 descs.putPortDesc(deltaDesc);
850 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100851 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700852 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700853 // same or outdated event, ignored.
854 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700855 return null;
856 }
857
858 if (oldPort == null) {
859 return createPort(device, newPort, ports);
860 } else {
Michal Machce774332017-01-25 11:02:55 +0100861 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700862 }
863 }
864 }
865
866 @Override
867 public List<Port> getPorts(DeviceId deviceId) {
868 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
869 if (ports == null) {
870 return Collections.emptyList();
871 }
872 return ImmutableList.copyOf(ports.values());
873 }
874
875 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700876 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
877 DeviceId deviceId) {
878 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
879 if (descs == null) {
Donghyeok Ho6de4fb92018-01-31 11:04:19 +0900880 return Stream.empty();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700881 }
882 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
883 final Optional<DeviceDescriptions> devDescs;
884 synchronized (descs) {
885 devDescs = Optional.ofNullable(descs.get(pid));
886 }
887 // DeviceDescriptions is concurrent access-safe
888 return devDescs
889 .map(dd -> dd.getPortDescs().values().stream()
890 .map(Timestamped::value))
891 .orElse(Stream.empty());
892 }
893
894 @Override
sangho538108b2015-04-08 14:29:20 -0700895 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200896 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700897
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200898 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
899 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
900 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
901
902 if (prvStatsMap != null) {
903 for (PortStatistics newStats : newStatsCollection) {
904 PortNumber port = PortNumber.portNumber(newStats.port());
905 PortStatistics prvStats = prvStatsMap.get(port);
906 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
907 PortStatistics deltaStats = builder.build();
908 if (prvStats != null) {
909 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
910 }
911 deltaStatsMap.put(port, deltaStats);
912 newStatsMap.put(port, newStats);
913 }
914 } else {
915 for (PortStatistics newStats : newStatsCollection) {
916 PortNumber port = PortNumber.portNumber(newStats.port());
917 newStatsMap.put(port, newStats);
918 }
sangho538108b2015-04-08 14:29:20 -0700919 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200920 devicePortDeltaStats.put(deviceId, deltaStatsMap);
921 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200922 // DeviceEvent returns null because of InternalPortStatsListener usage
923 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200924 }
925
926 /**
927 * Calculate delta statistics by subtracting previous from new statistics.
928 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700929 * @param deviceId device identifier
930 * @param prvStats previous port statistics
931 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200932 * @return PortStatistics
933 */
934 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
935 // calculate time difference
936 long deltaStatsSec, deltaStatsNano;
937 if (newStats.durationNano() < prvStats.durationNano()) {
938 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
939 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
940 } else {
941 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
942 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
943 }
944 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
945 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
946 .setPort(newStats.port())
947 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
948 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
949 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
950 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
951 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
952 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
953 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
954 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
955 .setDurationSec(deltaStatsSec)
956 .setDurationNano(deltaStatsNano)
957 .build();
958 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700959 }
960
961 @Override
962 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700963 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
964 if (portStats == null) {
965 return Collections.emptyList();
966 }
967 return ImmutableList.copyOf(portStats.values());
968 }
969
970 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530971 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
972 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
973 if (portStatsMap == null) {
974 return null;
975 }
976 PortStatistics portStats = portStatsMap.get(portNumber);
977 return portStats;
978 }
979
980 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200981 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
982 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
983 if (portStats == null) {
984 return Collections.emptyList();
985 }
986 return ImmutableList.copyOf(portStats.values());
987 }
988
989 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530990 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
991 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
992 if (portStatsMap == null) {
993 return null;
994 }
995 PortStatistics portStats = portStatsMap.get(portNumber);
996 return portStats;
997 }
998
999 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001000 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
1001 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1002 return ports == null ? null : ports.get(portNumber);
1003 }
1004
1005 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -07001006 public PortDescription getPortDescription(ProviderId pid,
1007 DeviceId deviceId,
1008 PortNumber portNumber) {
1009 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1010 if (descs == null) {
1011 return null;
1012 }
1013 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1014 final Optional<DeviceDescriptions> devDescs;
1015 synchronized (descs) {
1016 devDescs = Optional.ofNullable(descs.get(pid));
1017 }
1018 // DeviceDescriptions is concurrent access-safe
1019 return devDescs
1020 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1021 .map(Timestamped::value)
1022 .orElse(null);
1023 }
1024
1025 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001026 public boolean isAvailable(DeviceId deviceId) {
1027 return availableDevices.contains(deviceId);
1028 }
1029
1030 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001031 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001032 final NodeId myId = clusterService.getLocalNode().id();
1033 NodeId master = mastershipService.getMasterFor(deviceId);
1034
1035 // if there exist a master, forward
1036 // if there is no master, try to become one and process
1037
1038 boolean relinquishAtEnd = false;
1039 if (master == null) {
1040 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1041 if (myRole != MastershipRole.NONE) {
1042 relinquishAtEnd = true;
1043 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001044 log.debug("Temporarily requesting role for {} to remove", deviceId);
Jordan Haltermanf1c602d2017-10-18 11:26:52 -07001045 if (mastershipService.requestRoleFor(deviceId).join() == MastershipRole.MASTER) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001046 master = myId;
1047 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001048 }
1049
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001050 boolean isMaster = myId.equals(master);
1051
1052 // If this node is not the master, forward the request.
1053 if (!isMaster) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001054 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001055 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001056
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001057 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001058 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001059 /* error log:
1060 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1061 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001062 }
1063
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001064 // If this node is the master, get a timestamp. Otherwise, default to the current device timestamp.
1065 Timestamp timestamp = isMaster ? deviceClockService.getTimestamp(deviceId) : null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001066
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001067 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001068
1069 // If this node is the master, update peers.
1070 if (isMaster && event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001071 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001072 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001073 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Andrea Campanellabba1e882018-05-14 18:17:28 +02001074 notifyDelegateIfNotNull(event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001075 }
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001076
1077 // Relinquish mastership if acquired to remove the device.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001078 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001079 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001080 mastershipService.relinquishMastership(deviceId);
1081 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001082 return event;
1083 }
1084
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001085 private DeviceEvent removeDeviceInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001086
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001087 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001088 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001089 // accept removal request if given timestamp is newer than
1090 // the latest Timestamp from Primary provider
1091 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001092 if (primDescs == null) {
1093 return null;
1094 }
1095
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001096 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Jordan Haltermanebedbb52017-08-08 15:57:50 -07001097
1098 // If no timestamp is set, default the timestamp to the last timestamp for the device.
1099 if (timestamp == null) {
1100 timestamp = lastTimestamp;
1101 }
1102
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001103 if (timestamp.compareTo(lastTimestamp) <= 0) {
1104 // outdated event ignore
1105 return null;
1106 }
1107 removalRequest.put(deviceId, timestamp);
1108
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001109 Device device = devices.remove(deviceId);
1110 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001111 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1112 if (ports != null) {
1113 ports.clear();
1114 }
1115 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001116 descs.clear();
1117 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001118 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001119 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001120 }
1121
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001122 /**
1123 * Checks if given timestamp is superseded by removal request
1124 * with more recent timestamp.
1125 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001126 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001127 * @param timestampToCheck timestamp of an event to check
1128 * @return true if device is already removed
1129 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001130 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1131 Timestamp removalTimestamp = removalRequest.get(deviceId);
1132 if (removalTimestamp != null &&
Jordan Halterman8a0b3972017-08-15 16:14:18 -07001133 removalTimestamp.compareTo(timestampToCheck) > 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001134 // removalRequest is more recent
1135 return true;
1136 }
1137 return false;
1138 }
1139
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001140 /**
1141 * Returns a Device, merging description given from multiple Providers.
1142 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001143 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001144 * @param providerDescs Collection of Descriptions from multiple providers
1145 * @return Device instance
1146 */
1147 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001148 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001149
Thomas Vachuska444eda62014-10-28 13:09:42 -07001150 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001151
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001152 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001153
1154 DeviceDescriptions desc = providerDescs.get(primary);
1155
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001156 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001157 Type type = base.type();
1158 String manufacturer = base.manufacturer();
1159 String hwVersion = base.hwVersion();
1160 String swVersion = base.swVersion();
1161 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001162 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001163 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1164 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001165
1166 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1167 if (e.getKey().equals(primary)) {
1168 continue;
1169 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001170 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001171 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001172 // Currently assuming there will never be a key conflict between
1173 // providers
1174
1175 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001176 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001177 }
1178
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001179 return new DefaultDevice(primary, deviceId, type, manufacturer,
1180 hwVersion, swVersion, serialNumber,
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001181 chassisId, annotations.buildCompressed());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001182 }
1183
Marc De Leenheer88194c32015-05-29 22:10:59 -07001184 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1185 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001186 return new DefaultPort(device, number, isEnabled, description.type(),
1187 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001188 }
1189
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001190 /**
1191 * Returns a Port, merging description given from multiple Providers.
1192 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001193 * @param device device the port is on
1194 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001195 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001196 * @return Port instance
1197 */
1198 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001199 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001200
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001201 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001202 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001203 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001204 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001205 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001206 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001207 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1208 if (portDesc != null) {
1209 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001210 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001211 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001212 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001213 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001214 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001215 if (e.getKey().equals(primary)) {
1216 continue;
1217 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001218 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001219 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001220 // Currently assuming there will never be a key conflict between
1221 // providers
1222
1223 // annotation merging. not so efficient, should revisit later
1224 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1225 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001226 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1227 continue;
1228 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001229 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001230 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001231 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001232 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001233 }
1234 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001235 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001236 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001237 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001238 PortDescription current = portDesc.value();
1239 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001240 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001241 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001242 }
1243
1244 /**
1245 * @return primary ProviderID, or randomly chosen one if none exists
1246 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001247 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001248 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001249 ProviderId fallBackPrimary = null;
1250 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1251 if (!e.getKey().isAncillary()) {
1252 return e.getKey();
1253 } else if (fallBackPrimary == null) {
1254 // pick randomly as a fallback in case there is no primary
1255 fallBackPrimary = e.getKey();
1256 }
1257 }
1258 return fallBackPrimary;
1259 }
1260
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001261 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001262 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001263 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001264 return providerDescs.get(pid);
1265 }
1266
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001267 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001268 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001269 }
1270
Jonathan Hart7d656f42015-01-27 14:07:23 -08001271 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001272 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001273 }
Madan Jampani47c93732014-10-06 20:46:08 -07001274
Jonathan Hart7d656f42015-01-27 14:07:23 -08001275 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001276 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001277 }
1278
Palash Kala6c526062018-04-03 18:25:11 +09001279 private void notifyPeers(InternalDeviceStatusChangeEvent event) {
1280 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001281 }
1282
Jonathan Hart7d656f42015-01-27 14:07:23 -08001283 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001284 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001285 }
1286
Jonathan Hart7d656f42015-01-27 14:07:23 -08001287 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001288 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001289 }
1290
Jonathan Hart7d656f42015-01-27 14:07:23 -08001291 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001292 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1293 }
1294
1295 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1296 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001297 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001298 } catch (IOException e) {
1299 log.error("Failed to send" + event + " to " + recipient, e);
1300 }
1301 }
1302
Palash Kala6c526062018-04-03 18:25:11 +09001303 private void notifyPeer(NodeId recipient, InternalDeviceStatusChangeEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001304 try {
Palash Kala6c526062018-04-03 18:25:11 +09001305 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_STATUS_CHANGE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001306 } catch (IOException e) {
1307 log.error("Failed to send" + event + " to " + recipient, e);
1308 }
1309 }
1310
1311 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1312 try {
1313 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1314 } catch (IOException e) {
1315 log.error("Failed to send" + event + " to " + recipient, e);
1316 }
1317 }
1318
1319 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1320 try {
1321 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1322 } catch (IOException e) {
1323 log.error("Failed to send" + event + " to " + recipient, e);
1324 }
1325 }
1326
1327 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1328 try {
1329 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1330 } catch (IOException e) {
1331 log.error("Failed to send" + event + " to " + recipient, e);
1332 }
1333 }
1334
1335 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1336 final NodeId self = clusterService.getLocalNode().id();
1337
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001338 final int numDevices = deviceDescs.size();
1339 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1340 final int portsPerDevice = 8; // random factor to minimize reallocation
1341 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1342 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001343
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001344 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001345
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001346 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001347 synchronized (devDescs) {
1348
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001349 // send device offline timestamp
1350 Timestamp lOffline = this.offline.get(deviceId);
1351 if (lOffline != null) {
1352 adOffline.put(deviceId, lOffline);
1353 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001354
1355 for (Entry<ProviderId, DeviceDescriptions>
1356 prov : devDescs.entrySet()) {
1357
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001358 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001359 final ProviderId provId = prov.getKey();
1360 final DeviceDescriptions descs = prov.getValue();
1361
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001362 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001363 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001364
1365 for (Entry<PortNumber, Timestamped<PortDescription>>
1366 portDesc : descs.getPortDescs().entrySet()) {
1367
1368 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001369 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001370 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001371 }
1372 }
1373 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001374 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001375
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001376 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001377 }
1378
1379 /**
1380 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001381 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001382 * Notify sender about out-dated information using regular replication message.
1383 * Send back advertisement to sender if not in sync.
1384 *
1385 * @param advertisement to respond to
1386 */
1387 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1388
1389 final NodeId sender = advertisement.sender();
1390
1391 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1392 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1393 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1394
1395 // Fragments to request
1396 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1397 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1398
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001399 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001400 final DeviceId deviceId = de.getKey();
1401 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1402
1403 synchronized (lDevice) {
1404 // latestTimestamp across provider
1405 // Note: can be null initially
1406 Timestamp localLatest = offline.get(deviceId);
1407
1408 // handle device Ads
1409 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1410 final ProviderId provId = prov.getKey();
1411 final DeviceDescriptions lDeviceDescs = prov.getValue();
1412
1413 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1414
1415
1416 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1417 Timestamp advDevTimestamp = devAds.get(devFragId);
1418
Jonathan Hart403ea932015-02-20 16:23:00 -08001419 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1420 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001421 // remote does not have it or outdated, suggest
1422 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1423 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1424 // local is outdated, request
1425 reqDevices.add(devFragId);
1426 }
1427
1428 // handle port Ads
1429 for (Entry<PortNumber, Timestamped<PortDescription>>
1430 pe : lDeviceDescs.getPortDescs().entrySet()) {
1431
1432 final PortNumber num = pe.getKey();
1433 final Timestamped<PortDescription> lPort = pe.getValue();
1434
1435 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1436
1437 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001438 if (advPortTimestamp == null || lPort.isNewerThan(
1439 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001440 // remote does not have it or outdated, suggest
1441 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1442 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1443 // local is outdated, request
1444 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1445 reqPorts.add(portFragId);
1446 }
1447
1448 // remove port Ad already processed
1449 portAds.remove(portFragId);
1450 } // end local port loop
1451
1452 // remove device Ad already processed
1453 devAds.remove(devFragId);
1454
1455 // find latest and update
1456 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1457 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001458 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001459 localLatest = providerLatest;
1460 }
1461 } // end local provider loop
1462
1463 // checking if remote timestamp is more recent.
1464 Timestamp rOffline = offlineAds.get(deviceId);
jaegonkim73c21bd2018-01-13 10:52:02 +09001465 if (localLatest == null || (rOffline != null && rOffline.compareTo(localLatest) > 0)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001466 // remote offline timestamp suggests that the
1467 // device is off-line
1468 markOfflineInternal(deviceId, rOffline);
1469 }
1470
1471 Timestamp lOffline = offline.get(deviceId);
1472 if (lOffline != null && rOffline == null) {
1473 // locally offline, but remote is online, suggest offline
Palash Kala6c526062018-04-03 18:25:11 +09001474 notifyPeer(sender, new InternalDeviceStatusChangeEvent(deviceId, lOffline, false));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001475 }
1476
1477 // remove device offline Ad already processed
1478 offlineAds.remove(deviceId);
1479 } // end local device loop
1480 } // device lock
1481
1482 // If there is any Ads left, request them
1483 log.trace("Ads left {}, {}", devAds, portAds);
1484 reqDevices.addAll(devAds.keySet());
1485 reqPorts.addAll(portAds.keySet());
1486
1487 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1488 log.trace("Nothing to request to remote peer {}", sender);
1489 return;
1490 }
1491
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001492 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001493
1494 // 2-way Anti-Entropy for now
1495 try {
1496 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1497 } catch (IOException e) {
1498 log.error("Failed to send response advertisement to " + sender, e);
1499 }
1500
1501// Sketch of 3-way Anti-Entropy
1502// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1503// ClusterMessage message = new ClusterMessage(
1504// clusterService.getLocalNode().id(),
1505// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1506// SERIALIZER.encode(request));
1507//
1508// try {
1509// clusterCommunicator.unicast(message, advertisement.sender());
1510// } catch (IOException e) {
1511// log.error("Failed to send advertisement reply to "
1512// + advertisement.sender(), e);
1513// }
Madan Jampani47c93732014-10-06 20:46:08 -07001514 }
1515
Madan Jampani255a58b2014-10-09 12:08:20 -07001516 private void notifyDelegateIfNotNull(DeviceEvent event) {
1517 if (event != null) {
1518 notifyDelegate(event);
1519 }
1520 }
1521
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001522 private final class SendAdvertisementTask implements Runnable {
1523
1524 @Override
1525 public void run() {
1526 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001527 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001528 return;
1529 }
1530
1531 try {
1532 final NodeId self = clusterService.getLocalNode().id();
1533 Set<ControllerNode> nodes = clusterService.getNodes();
1534
1535 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1536 .transform(toNodeId())
1537 .toList();
1538
1539 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001540 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001541 return;
1542 }
1543
1544 NodeId peer;
1545 do {
1546 int idx = RandomUtils.nextInt(0, nodeIds.size());
1547 peer = nodeIds.get(idx);
1548 } while (peer.equals(self));
1549
1550 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1551
1552 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001553 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001554 return;
1555 }
1556
1557 try {
1558 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1559 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001560 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001561 return;
1562 }
1563 } catch (Exception e) {
1564 // catch all Exception to avoid Scheduled task being suppressed.
1565 log.error("Exception thrown while sending advertisement", e);
1566 }
1567 }
1568 }
1569
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001570 private void handleDeviceEvent(InternalDeviceEvent event) {
1571 ProviderId providerId = event.providerId();
1572 DeviceId deviceId = event.deviceId();
1573 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001574
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001575 try {
1576 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1577 deviceDescription));
1578 } catch (Exception e) {
1579 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001580 }
1581 }
1582
Palash Kala6c526062018-04-03 18:25:11 +09001583 private void handleDeviceStatusChangeEvent(InternalDeviceStatusChangeEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001584 DeviceId deviceId = event.deviceId();
1585 Timestamp timestamp = event.timestamp();
Palash Kala6c526062018-04-03 18:25:11 +09001586 Boolean available = event.available();
Madan Jampani25322532014-10-08 11:20:38 -07001587
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001588 try {
Palash Kala6c526062018-04-03 18:25:11 +09001589 if (available) {
1590 notifyDelegateIfNotNull(markOnlineInternal(deviceId, timestamp));
1591 } else {
1592 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1593 }
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001594 } catch (Exception e) {
Palash Kala6c526062018-04-03 18:25:11 +09001595 log.warn("Exception thrown handling device status change event", e);
Madan Jampani25322532014-10-08 11:20:38 -07001596 }
1597 }
1598
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001599 private void handleRemoveRequest(DeviceId did) {
1600 try {
Jayasree Ghosh7d96d6a2017-02-27 18:35:32 +05301601 DeviceEvent event = removeDevice(did);
1602 notifyDelegateIfNotNull(event);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001603 } catch (Exception e) {
1604 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001605 }
1606 }
1607
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001608 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1609 DeviceId deviceId = event.deviceId();
1610 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001611
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001612 try {
1613 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1614 } catch (Exception e) {
1615 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001616 }
1617 }
1618
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001619 private void handlePortEvent(InternalPortEvent event) {
1620 ProviderId providerId = event.providerId();
1621 DeviceId deviceId = event.deviceId();
1622 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001623
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001624 if (getDevice(deviceId) == null) {
1625 log.debug("{} not found on this node yet, ignoring.", deviceId);
1626 // Note: dropped information will be recovered by anti-entropy
1627 return;
1628 }
Madan Jampani47c93732014-10-06 20:46:08 -07001629
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001630 try {
1631 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1632 } catch (Exception e) {
1633 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001634 }
1635 }
1636
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001637 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1638 ProviderId providerId = event.providerId();
1639 DeviceId deviceId = event.deviceId();
1640 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001641
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001642 if (getDevice(deviceId) == null) {
1643 log.debug("{} not found on this node yet, ignoring.", deviceId);
1644 // Note: dropped information will be recovered by anti-entropy
1645 return;
1646 }
Madan Jampani47c93732014-10-06 20:46:08 -07001647
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001648 try {
1649 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1650 } catch (Exception e) {
1651 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001652 }
1653 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001654
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001655 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1656 try {
1657 handleAdvertisement(advertisement);
1658 } catch (Exception e) {
1659 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001660 }
1661 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001662
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001663 private class InternalPortStatsListener
1664 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1665 @Override
1666 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1667 if (event.type() == PUT) {
1668 Device device = devices.get(event.key());
1669 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001670 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001671 }
1672 }
1673 }
1674 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001675}