blob: b95066ceb047c1209aa0304b9af0b95487791e4e [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
Ray Milkey2bf5ea72017-06-01 09:03:34 -070018import java.io.IOException;
19import java.util.ArrayList;
20import java.util.Collection;
21import java.util.Collections;
22import java.util.HashMap;
23import java.util.HashSet;
24import java.util.Iterator;
25import java.util.List;
26import java.util.Map;
27import java.util.Map.Entry;
28import java.util.Objects;
29import java.util.Optional;
30import java.util.Set;
31import java.util.concurrent.ConcurrentHashMap;
32import java.util.concurrent.ConcurrentMap;
33import java.util.concurrent.ExecutorService;
34import java.util.concurrent.ScheduledExecutorService;
35import java.util.concurrent.TimeUnit;
36import java.util.function.Consumer;
37import java.util.stream.Stream;
38
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070039import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070040import org.apache.felix.scr.annotations.Activate;
41import org.apache.felix.scr.annotations.Component;
42import org.apache.felix.scr.annotations.Deactivate;
43import org.apache.felix.scr.annotations.Reference;
44import org.apache.felix.scr.annotations.ReferenceCardinality;
45import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080046import org.onlab.packet.ChassisId;
47import org.onlab.util.KryoNamespace;
Brian O'Connorabafb502014-12-02 22:26:20 -080048import org.onosproject.cluster.ClusterService;
49import org.onosproject.cluster.ControllerNode;
50import org.onosproject.cluster.NodeId;
51import org.onosproject.mastership.MastershipService;
52import org.onosproject.mastership.MastershipTerm;
53import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070054import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.net.AnnotationsUtil;
56import org.onosproject.net.DefaultAnnotations;
57import org.onosproject.net.DefaultDevice;
58import org.onosproject.net.DefaultPort;
59import org.onosproject.net.Device;
60import org.onosproject.net.Device.Type;
61import org.onosproject.net.DeviceId;
62import org.onosproject.net.MastershipRole;
63import org.onosproject.net.Port;
64import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070065import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080066import org.onosproject.net.device.DeviceClockService;
67import org.onosproject.net.device.DeviceDescription;
68import org.onosproject.net.device.DeviceEvent;
69import org.onosproject.net.device.DeviceStore;
70import org.onosproject.net.device.DeviceStoreDelegate;
71import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070072import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080073import org.onosproject.net.provider.ProviderId;
74import org.onosproject.store.AbstractStore;
75import org.onosproject.store.Timestamp;
76import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
Brian O'Connorabafb502014-12-02 22:26:20 -080077import org.onosproject.store.cluster.messaging.MessageSubject;
78import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070079import org.onosproject.store.serializers.KryoNamespaces;
HIGUCHI Yutae7290652016-05-18 11:29:01 -070080import org.onosproject.store.serializers.StoreSerializer;
Brian O'Connor6de2e202015-05-21 14:30:41 -070081import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070082import org.onosproject.store.service.EventuallyConsistentMap;
83import org.onosproject.store.service.EventuallyConsistentMapEvent;
84import org.onosproject.store.service.EventuallyConsistentMapListener;
85import org.onosproject.store.service.MultiValuedTimestamp;
86import org.onosproject.store.service.StorageService;
87import org.onosproject.store.service.WallClockTimestamp;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070088import org.slf4j.Logger;
89
Ray Milkey2bf5ea72017-06-01 09:03:34 -070090import com.google.common.collect.FluentIterable;
91import com.google.common.collect.ImmutableList;
92import com.google.common.collect.Maps;
93import com.google.common.collect.Sets;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070094
95import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070096import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070097import static com.google.common.base.Verify.verify;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -080098import static java.util.concurrent.Executors.newCachedThreadPool;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080099import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800100import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800101import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800102import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
Ray Milkey9ef22232016-07-14 12:42:37 -0700103import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED;
104import static org.onosproject.net.device.DeviceEvent.Type.PORT_ADDED;
105import static org.onosproject.net.device.DeviceEvent.Type.PORT_REMOVED;
106import static org.onosproject.net.device.DeviceEvent.Type.PORT_STATS_UPDATED;
107import static org.onosproject.net.device.DeviceEvent.Type.PORT_UPDATED;
108import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700109import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE;
110import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVED;
Ray Milkey9ef22232016-07-14 12:42:37 -0700111import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700112import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_UPDATE;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700113import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE;
114import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_UPDATE;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700115import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800116import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700117
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700118/**
119 * Manages inventory of infrastructure devices using gossip protocol to distribute
120 * information.
121 */
122@Component(immediate = true)
123@Service
124public class GossipDeviceStore
125 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
126 implements DeviceStore {
127
128 private final Logger log = getLogger(getClass());
129
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700130 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800131 // Timeout in milliseconds to process device or ports on remote master node
132 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700133
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700134 // innerMap is used to lock a Device, thus instance should never be replaced.
135 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700136 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700137 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700138
139 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700140 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
141 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700142
143 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200144 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700145 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
146 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700147
148 // to be updated under Device lock
149 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
150 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700151
152 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700153 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700154
155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700156 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700157
Madan Jampani47c93732014-10-06 20:46:08 -0700158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700159 protected StorageService storageService;
160
161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700162 protected ClusterCommunicationService clusterCommunicator;
163
Madan Jampani53e44e62014-10-07 12:39:51 -0700164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
165 protected ClusterService clusterService;
166
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
168 protected MastershipService mastershipService;
169
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800170 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
171 protected MastershipTermService termService;
172
173
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700174 protected static final StoreSerializer SERIALIZER = StoreSerializer.using(KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800175 .register(DistributedStoreSerializers.STORE_COMMON)
176 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
177 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
178 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700179 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800180 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
181 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700182 .register(DeviceAntiEntropyAdvertisement.class)
183 .register(DeviceFragmentId.class)
184 .register(PortFragmentId.class)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700185 .build("GossipDevice"));
Madan Jampani53e44e62014-10-07 12:39:51 -0700186
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800187 private ExecutorService executor;
188
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800189 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700190
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800191 // TODO make these anti-entropy parameters configurable
192 private long initialDelaySec = 5;
193 private long periodSec = 5;
194
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700195 @Activate
196 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800197 executor = newCachedThreadPool(groupedThreads("onos/device", "fg-%d", log));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800198
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800199 backgroundExecutor =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800200 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d", log)));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700201
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700202 addSubscriber(DEVICE_UPDATE, this::handleDeviceEvent);
203 addSubscriber(DEVICE_OFFLINE, this::handleDeviceOfflineEvent);
204 addSubscriber(DEVICE_REMOVE_REQ, this::handleRemoveRequest);
205 addSubscriber(DEVICE_REMOVED, this::handleDeviceRemovedEvent);
206 addSubscriber(PORT_UPDATE, this::handlePortEvent);
207 addSubscriber(PORT_STATUS_UPDATE, this::handlePortStatusEvent);
208 addSubscriber(DEVICE_ADVERTISE, this::handleDeviceAdvertisement);
Madan Jampani2af244a2015-02-22 13:12:01 -0800209
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700210 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800211 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700212 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700213
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700214 // Create a distributed map for port stats.
215 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
216 .register(KryoNamespaces.API)
HIGUCHI Yuta03666a32016-05-18 11:49:09 -0700217 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
218 .register(MultiValuedTimestamp.class);
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700219
220 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
221 .withName("port-stats")
222 .withSerializer(deviceDataSerializer)
223 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700224 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700225 .withTombstonesDisabled()
226 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200227 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
228 eventuallyConsistentMapBuilder()
229 .withName("port-stats-delta")
230 .withSerializer(deviceDataSerializer)
231 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
232 .withTimestampProvider((k, v) -> new WallClockTimestamp())
233 .withTombstonesDisabled()
234 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700235 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700236 log.info("Started");
237 }
238
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700239 private <M> void addSubscriber(MessageSubject subject, Consumer<M> handler) {
240 clusterCommunicator.addSubscriber(subject, SERIALIZER::decode, handler, executor);
241 }
242
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700243 @Deactivate
244 public void deactivate() {
Frank Wange0eb5ce2016-07-01 18:21:25 +0800245 devicePortStats.removeListener(portStatsListener);
Madan Jampani632f16b2015-08-11 12:42:59 -0700246 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200247 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800248 executor.shutdownNow();
249
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800250 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700251 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800252 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700253 log.error("Timeout during executor shutdown");
254 }
255 } catch (InterruptedException e) {
256 log.error("Error during executor shutdown", e);
257 }
258
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700259 deviceDescs.clear();
260 devices.clear();
261 devicePorts.clear();
262 availableDevices.clear();
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700263 clusterCommunicator.removeSubscriber(DEVICE_UPDATE);
264 clusterCommunicator.removeSubscriber(DEVICE_OFFLINE);
265 clusterCommunicator.removeSubscriber(DEVICE_REMOVE_REQ);
266 clusterCommunicator.removeSubscriber(DEVICE_REMOVED);
267 clusterCommunicator.removeSubscriber(PORT_UPDATE);
268 clusterCommunicator.removeSubscriber(PORT_STATUS_UPDATE);
269 clusterCommunicator.removeSubscriber(DEVICE_ADVERTISE);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700270 log.info("Stopped");
271 }
272
273 @Override
274 public int getDeviceCount() {
275 return devices.size();
276 }
277
278 @Override
mskala0d0c6832017-07-12 11:21:23 +0200279 public int getAvailableDeviceCount() {
280 return availableDevices.size();
281 }
282
283 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700284 public Iterable<Device> getDevices() {
285 return Collections.unmodifiableCollection(devices.values());
286 }
287
288 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800289 public Iterable<Device> getAvailableDevices() {
290 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700291 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800292 }
293
294 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700295 public Device getDevice(DeviceId deviceId) {
296 return devices.get(deviceId);
297 }
298
299 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700300 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700301 DeviceId deviceId,
302 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800303 NodeId localNode = clusterService.getLocalNode().id();
304 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
305
306 // Process device update only if we're the master,
307 // otherwise signal the actual master.
308 DeviceEvent deviceEvent = null;
309 if (localNode.equals(deviceNode)) {
310
311 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
312 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
313 final Timestamped<DeviceDescription> mergedDesc;
314 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
315
316 synchronized (device) {
317 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
318 mergedDesc = device.get(providerId).getDeviceDesc();
319 }
320
321 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700322 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
helenyrwufd296b62016-06-22 17:43:02 -0700323 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800324 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
325 }
326
327 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700328 return null;
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700329 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800330
331 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700332 }
333
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700334 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700335 DeviceId deviceId,
336 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700337
338 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800339 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700340 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700341
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800342 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700343 // locking per device
344
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700345 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
346 log.debug("Ignoring outdated event: {}", deltaDesc);
347 return null;
348 }
349
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800350 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700351
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700352 final Device oldDevice = devices.get(deviceId);
353 final Device newDevice;
354
355 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700356 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700357 // on new device or valid update
358 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800359 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700360 } else {
361 // outdated event, ignored.
362 return null;
363 }
364 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700365 // REGISTER
366 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700367 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700368 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700369 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700370 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700371 } else {
372 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700373 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
374 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700375 }
376 }
377 }
378
379 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700380 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700381 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700382 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700383
384 // update composed device cache
385 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
386 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700387 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
388 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700389
390 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700391 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700392 }
393
394 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
395 }
396
397 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700398 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700399 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700400 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700401 Device newDevice, Timestamp newTimestamp,
402 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700403 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700404 boolean propertiesChanged =
405 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700406 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
mskala4b2081a2017-06-12 16:39:50 +0200407 !Objects.equals(oldDevice.providerId(), newDevice.providerId()) ||
408 !Objects.equals(oldDevice.chassisId(), newDevice.chassisId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700409 boolean annotationsChanged =
410 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700411
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700412 // Primary providers can respond to all changes, but ancillary ones
413 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800414 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700415 if ((providerId.isAncillary() && annotationsChanged) ||
416 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700417 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
418 if (!replaced) {
419 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700420 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800421 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700422 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700423
alshabibdc5d8bd2015-11-02 15:41:29 -0800424 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700425 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800426
helenyrwufd296b62016-06-22 17:43:02 -0700427 if (!providerId.isAncillary() && forceAvailable) {
alshabibdc5d8bd2015-11-02 15:41:29 -0800428 boolean wasOnline = availableDevices.contains(newDevice.id());
429 markOnline(newDevice.id(), newTimestamp);
430 if (!wasOnline) {
431 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
432 }
433 }
434 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700435 }
436
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700437 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700438 // update composed device cache
439 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
440 verify(oldDevice == null,
441 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
442 providerId, oldDevice, newDevice);
443
444 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700445 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700446 }
447
448 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
449 }
450
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700451 @Override
452 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700453 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
454 }
455
456 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700457 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700458 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700459 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700460 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800461 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700462 }
463 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700464 }
465
466 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700467 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700468 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700469
470 // locking device
471 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700472 // accept off-line if given timestamp is newer than
473 // the latest Timestamp from Primary provider
474 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
Thomas Vachuska4bd10b92016-12-15 10:13:38 -0800475 if (primDescs == null) {
476 return null;
477 }
478
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700479 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
Saritha781984f2017-06-27 09:46:02 +0530480 if (lastTimestamp == null) {
481 lastTimestamp = deviceClockService.getTimestamp(deviceId);
482 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700483 if (timestamp.compareTo(lastTimestamp) <= 0) {
484 // outdated event ignore
485 return null;
486 }
487
488 offline.put(deviceId, timestamp);
489
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700490 Device device = devices.get(deviceId);
491 if (device == null) {
492 return null;
493 }
494 boolean removed = availableDevices.remove(deviceId);
495 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700496 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700497 }
498 return null;
499 }
500 }
501
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700502 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700503 public boolean markOnline(DeviceId deviceId) {
504 if (devices.containsKey(deviceId)) {
505 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
506 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
507 synchronized (deviceLock) {
508 if (markOnline(deviceId, timestamp)) {
509 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
510 return true;
511 } else {
512 return false;
513 }
514 }
515 }
516 log.warn("Device {} does not exist in store", deviceId);
517 return false;
518
519 }
520
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700521 /**
522 * Marks the device as available if the given timestamp is not outdated,
523 * compared to the time the device has been marked offline.
524 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700525 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700526 * @param timestamp of the event triggering this change.
527 * @return true if availability change request was accepted and changed the state
528 */
529 // Guarded by deviceDescs value (=Device lock)
530 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
531 // accept on-line if given timestamp is newer than
532 // the latest offline request Timestamp
533 Timestamp offlineTimestamp = offline.get(deviceId);
534 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700535 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700536
537 offline.remove(deviceId);
538 return availableDevices.add(deviceId);
539 }
540 return false;
541 }
542
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700543 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700544 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700545 DeviceId deviceId,
546 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700547
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800548 NodeId localNode = clusterService.getLocalNode().id();
549 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
550 // since it will trigger distributed store read.
551 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
552 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
553 // If we don't care much about topology performance, then it might be OK.
554 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700555
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800556 // Process port update only if we're the master of the device,
557 // otherwise signal the actual master.
558 List<DeviceEvent> deviceEvents = null;
559 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700560
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800561 final Timestamp newTimestamp;
562 try {
563 newTimestamp = deviceClockService.getTimestamp(deviceId);
564 } catch (IllegalStateException e) {
565 log.info("Timestamp was not available for device {}", deviceId);
566 log.debug(" discarding {}", portDescriptions);
567 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700568
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800569 // Possible situation:
570 // Device connected and became master for short period of time,
571 // but lost mastership before this instance had the chance to
572 // retrieve term information.
573
574 // Information dropped here is expected to be recoverable by
575 // device probing after mastership change
576
577 return Collections.emptyList();
578 }
579 log.debug("timestamp for {} {}", deviceId, newTimestamp);
580
581 final Timestamped<List<PortDescription>> timestampedInput
582 = new Timestamped<>(portDescriptions, newTimestamp);
583 final Timestamped<List<PortDescription>> merged;
584
585 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
586
587 synchronized (device) {
588 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
589 final DeviceDescriptions descs = device.get(providerId);
590 List<PortDescription> mergedList =
591 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700592 .transform(input ->
593 // lookup merged port description
594 descs.getPortDesc(input.portNumber()).value()
595 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700596 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800597 }
598
599 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700600 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700601 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800602 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
603 }
604
605 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700606 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700607 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700608
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800609 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700610 }
611
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700612 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700613 DeviceId deviceId,
614 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700615
616 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700617 if (device == null) {
618 log.debug("Device is no longer valid: {}", deviceId);
619 return Collections.emptyList();
620 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700621
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700622 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700623 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
624
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700625 List<DeviceEvent> events = new ArrayList<>();
626 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700627
628 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
629 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700630 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700631 }
632
633 DeviceDescriptions descs = descsMap.get(providerId);
634 // every provider must provide DeviceDescription.
635 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700636 "Device description for Device ID %s from Provider %s was not found",
637 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700638
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700639 Map<PortNumber, Port> ports = getPortMap(deviceId);
640
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700641 final Timestamp newTimestamp = portDescriptions.timestamp();
642
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700643 // Add new ports
644 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700645 for (PortDescription portDescription : portDescriptions.value()) {
646 final PortNumber number = portDescription.portNumber();
647 processed.add(number);
648
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700649 final Port oldPort = ports.get(number);
650 final Port newPort;
651
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700652
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700653 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
654 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700655 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700656 // on new port or valid update
657 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700658 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700659 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700660 newPort = composePort(device, number, descsMap);
661 } else {
662 // outdated event, ignored.
663 continue;
664 }
665
666 events.add(oldPort == null ?
667 createPort(device, newPort, ports) :
668 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700669 }
670
671 events.addAll(pruneOldPorts(device, ports, processed));
672 }
673 return FluentIterable.from(events).filter(notNull()).toList();
674 }
675
676 // Creates a new port based on the port description adds it to the map and
677 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700678 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700679 private DeviceEvent createPort(Device device, Port newPort,
680 Map<PortNumber, Port> ports) {
681 ports.put(newPort.number(), newPort);
682 return new DeviceEvent(PORT_ADDED, device, newPort);
683 }
684
685 // Checks if the specified port requires update and if so, it replaces the
686 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700687 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700688 private DeviceEvent updatePort(Device device, Port oldPort,
689 Port newPort,
690 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100691
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700692 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700693 oldPort.type() != newPort.type() ||
694 oldPort.portSpeed() != newPort.portSpeed() ||
695 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700696 ports.put(oldPort.number(), newPort);
697 return new DeviceEvent(PORT_UPDATED, device, newPort);
698 }
699 return null;
700 }
701
Michal Machce774332017-01-25 11:02:55 +0100702 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
703
704 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
705 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
706
707 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
708 }
709
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700710 // Prunes the specified list of ports based on which ports are in the
711 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700712 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700713 private List<DeviceEvent> pruneOldPorts(Device device,
714 Map<PortNumber, Port> ports,
715 Set<PortNumber> processed) {
716 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700717 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700718 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700719 Entry<PortNumber, Port> e = iterator.next();
720 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700721 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700722 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700723 iterator.remove();
724 }
725 }
726 return events;
727 }
728
729 // Gets the map of ports for the specified device; if one does not already
730 // exist, it creates and registers a new one.
731 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700732 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700733 }
734
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700735 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700736 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700737 Map<ProviderId, DeviceDescriptions> r;
738 r = deviceDescs.get(deviceId);
739 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700740 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700741 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
742 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
743 if (concurrentlyAdded != null) {
744 r = concurrentlyAdded;
745 }
746 }
747 return r;
748 }
749
750 // Guarded by deviceDescs value (=Device lock)
751 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
752 Map<ProviderId, DeviceDescriptions> device,
753 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700754 synchronized (device) {
755 DeviceDescriptions r = device.get(providerId);
756 if (r == null) {
757 r = new DeviceDescriptions(deltaDesc);
758 device.put(providerId, r);
759 }
760 return r;
761 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700762 }
763
764 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700765 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
766 DeviceId deviceId,
767 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700768 final Timestamp newTimestamp;
769 try {
770 newTimestamp = deviceClockService.getTimestamp(deviceId);
771 } catch (IllegalStateException e) {
772 log.info("Timestamp was not available for device {}", deviceId);
773 log.debug(" discarding {}", portDescription);
774 // Failed to generate timestamp. Ignoring.
775 // See updatePorts comment
776 return null;
777 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700778 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700779 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700780 final DeviceEvent event;
781 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800782 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
783 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700784 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800785 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700786 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700787 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700788 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700789 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700790 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800791 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700792 }
793 return event;
794 }
795
796 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700797 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700798 Device device = devices.get(deviceId);
799 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
800
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700801 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700802 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
803
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700804 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700805
806 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
807 log.debug("Ignoring outdated event: {}", deltaDesc);
808 return null;
809 }
810
811 DeviceDescriptions descs = descsMap.get(providerId);
812 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700813 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700814 "Device description for Device ID %s from Provider %s was not found",
815 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700816
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700817 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
818 final PortNumber number = deltaDesc.value().portNumber();
819 final Port oldPort = ports.get(number);
820 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700821 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100822 boolean toDelete = false;
823
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700824 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700825 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700826 // on new port or valid update
827 // update description
828 descs.putPortDesc(deltaDesc);
829 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100830 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700831 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700832 // same or outdated event, ignored.
833 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700834 return null;
835 }
836
837 if (oldPort == null) {
838 return createPort(device, newPort, ports);
839 } else {
Michal Machce774332017-01-25 11:02:55 +0100840 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700841 }
842 }
843 }
844
845 @Override
846 public List<Port> getPorts(DeviceId deviceId) {
847 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
848 if (ports == null) {
849 return Collections.emptyList();
850 }
851 return ImmutableList.copyOf(ports.values());
852 }
853
854 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700855 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
856 DeviceId deviceId) {
857 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
858 if (descs == null) {
859 return null;
860 }
861 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
862 final Optional<DeviceDescriptions> devDescs;
863 synchronized (descs) {
864 devDescs = Optional.ofNullable(descs.get(pid));
865 }
866 // DeviceDescriptions is concurrent access-safe
867 return devDescs
868 .map(dd -> dd.getPortDescs().values().stream()
869 .map(Timestamped::value))
870 .orElse(Stream.empty());
871 }
872
873 @Override
sangho538108b2015-04-08 14:29:20 -0700874 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200875 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700876
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200877 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
878 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
879 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
880
881 if (prvStatsMap != null) {
882 for (PortStatistics newStats : newStatsCollection) {
883 PortNumber port = PortNumber.portNumber(newStats.port());
884 PortStatistics prvStats = prvStatsMap.get(port);
885 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
886 PortStatistics deltaStats = builder.build();
887 if (prvStats != null) {
888 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
889 }
890 deltaStatsMap.put(port, deltaStats);
891 newStatsMap.put(port, newStats);
892 }
893 } else {
894 for (PortStatistics newStats : newStatsCollection) {
895 PortNumber port = PortNumber.portNumber(newStats.port());
896 newStatsMap.put(port, newStats);
897 }
sangho538108b2015-04-08 14:29:20 -0700898 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200899 devicePortDeltaStats.put(deviceId, deltaStatsMap);
900 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200901 // DeviceEvent returns null because of InternalPortStatsListener usage
902 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200903 }
904
905 /**
906 * Calculate delta statistics by subtracting previous from new statistics.
907 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700908 * @param deviceId device identifier
909 * @param prvStats previous port statistics
910 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200911 * @return PortStatistics
912 */
913 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
914 // calculate time difference
915 long deltaStatsSec, deltaStatsNano;
916 if (newStats.durationNano() < prvStats.durationNano()) {
917 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
918 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
919 } else {
920 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
921 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
922 }
923 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
924 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
925 .setPort(newStats.port())
926 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
927 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
928 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
929 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
930 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
931 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
932 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
933 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
934 .setDurationSec(deltaStatsSec)
935 .setDurationNano(deltaStatsNano)
936 .build();
937 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700938 }
939
940 @Override
941 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700942 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
943 if (portStats == null) {
944 return Collections.emptyList();
945 }
946 return ImmutableList.copyOf(portStats.values());
947 }
948
949 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530950 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
951 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
952 if (portStatsMap == null) {
953 return null;
954 }
955 PortStatistics portStats = portStatsMap.get(portNumber);
956 return portStats;
957 }
958
959 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200960 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
961 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
962 if (portStats == null) {
963 return Collections.emptyList();
964 }
965 return ImmutableList.copyOf(portStats.values());
966 }
967
968 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530969 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
970 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
971 if (portStatsMap == null) {
972 return null;
973 }
974 PortStatistics portStats = portStatsMap.get(portNumber);
975 return portStats;
976 }
977
978 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700979 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
980 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
981 return ports == null ? null : ports.get(portNumber);
982 }
983
984 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700985 public PortDescription getPortDescription(ProviderId pid,
986 DeviceId deviceId,
987 PortNumber portNumber) {
988 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
989 if (descs == null) {
990 return null;
991 }
992 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
993 final Optional<DeviceDescriptions> devDescs;
994 synchronized (descs) {
995 devDescs = Optional.ofNullable(descs.get(pid));
996 }
997 // DeviceDescriptions is concurrent access-safe
998 return devDescs
999 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1000 .map(Timestamped::value)
1001 .orElse(null);
1002 }
1003
1004 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001005 public boolean isAvailable(DeviceId deviceId) {
1006 return availableDevices.contains(deviceId);
1007 }
1008
1009 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001010 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001011 final NodeId myId = clusterService.getLocalNode().id();
1012 NodeId master = mastershipService.getMasterFor(deviceId);
1013
1014 // if there exist a master, forward
1015 // if there is no master, try to become one and process
1016
1017 boolean relinquishAtEnd = false;
1018 if (master == null) {
1019 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1020 if (myRole != MastershipRole.NONE) {
1021 relinquishAtEnd = true;
1022 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001023 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001024 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001025 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -07001026 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001027 master = myId;
1028 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001029 }
1030
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001031 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001032 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001033 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001034
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001035 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001036 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001037 /* error log:
1038 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1039 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001040
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001041 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001042 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001043 }
1044
1045 // I have control..
1046
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -07001047 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001048 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001049 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001050 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001051 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001052 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001053 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001054 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001055 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001056 mastershipService.relinquishMastership(deviceId);
1057 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001058 return event;
1059 }
1060
1061 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
1062 Timestamp timestamp) {
1063
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001064 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001065 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001066 // accept removal request if given timestamp is newer than
1067 // the latest Timestamp from Primary provider
1068 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001069 if (primDescs == null) {
1070 return null;
1071 }
1072
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001073 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
1074 if (timestamp.compareTo(lastTimestamp) <= 0) {
1075 // outdated event ignore
1076 return null;
1077 }
1078 removalRequest.put(deviceId, timestamp);
1079
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001080 Device device = devices.remove(deviceId);
1081 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001082 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1083 if (ports != null) {
1084 ports.clear();
1085 }
1086 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001087 descs.clear();
1088 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001089 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001090 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001091 }
1092
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001093 /**
1094 * Checks if given timestamp is superseded by removal request
1095 * with more recent timestamp.
1096 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001097 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001098 * @param timestampToCheck timestamp of an event to check
1099 * @return true if device is already removed
1100 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001101 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1102 Timestamp removalTimestamp = removalRequest.get(deviceId);
1103 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001104 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001105 // removalRequest is more recent
1106 return true;
1107 }
1108 return false;
1109 }
1110
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001111 /**
1112 * Returns a Device, merging description given from multiple Providers.
1113 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001114 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001115 * @param providerDescs Collection of Descriptions from multiple providers
1116 * @return Device instance
1117 */
1118 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001119 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001120
Thomas Vachuska444eda62014-10-28 13:09:42 -07001121 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001122
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001123 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001124
1125 DeviceDescriptions desc = providerDescs.get(primary);
1126
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001127 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001128 Type type = base.type();
1129 String manufacturer = base.manufacturer();
1130 String hwVersion = base.hwVersion();
1131 String swVersion = base.swVersion();
1132 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001133 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001134 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1135 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001136
1137 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1138 if (e.getKey().equals(primary)) {
1139 continue;
1140 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001141 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001142 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001143 // Currently assuming there will never be a key conflict between
1144 // providers
1145
1146 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001147 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001148 }
1149
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001150 return new DefaultDevice(primary, deviceId, type, manufacturer,
1151 hwVersion, swVersion, serialNumber,
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001152 chassisId, annotations.build());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001153 }
1154
Marc De Leenheer88194c32015-05-29 22:10:59 -07001155 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1156 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001157 return new DefaultPort(device, number, isEnabled, description.type(),
1158 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001159 }
1160
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001161 /**
1162 * Returns a Port, merging description given from multiple Providers.
1163 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001164 * @param device device the port is on
1165 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001166 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001167 * @return Port instance
1168 */
1169 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001170 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001171
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001172 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001173 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001174 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001175 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001176 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001177 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001178 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1179 if (portDesc != null) {
1180 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001181 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001182 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001183 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001184 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001185 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001186 if (e.getKey().equals(primary)) {
1187 continue;
1188 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001189 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001190 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001191 // Currently assuming there will never be a key conflict between
1192 // providers
1193
1194 // annotation merging. not so efficient, should revisit later
1195 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1196 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001197 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1198 continue;
1199 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001200 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001201 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001202 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001203 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001204 }
1205 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001206 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001207 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001208 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001209 PortDescription current = portDesc.value();
1210 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001211 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001212 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001213 }
1214
1215 /**
1216 * @return primary ProviderID, or randomly chosen one if none exists
1217 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001218 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001219 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001220 ProviderId fallBackPrimary = null;
1221 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1222 if (!e.getKey().isAncillary()) {
1223 return e.getKey();
1224 } else if (fallBackPrimary == null) {
1225 // pick randomly as a fallback in case there is no primary
1226 fallBackPrimary = e.getKey();
1227 }
1228 }
1229 return fallBackPrimary;
1230 }
1231
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001232 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001233 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001234 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001235 return providerDescs.get(pid);
1236 }
1237
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001238 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001239 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001240 }
1241
Jonathan Hart7d656f42015-01-27 14:07:23 -08001242 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001243 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001244 }
Madan Jampani47c93732014-10-06 20:46:08 -07001245
Jonathan Hart7d656f42015-01-27 14:07:23 -08001246 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001247 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001248 }
1249
Jonathan Hart7d656f42015-01-27 14:07:23 -08001250 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001251 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001252 }
1253
Jonathan Hart7d656f42015-01-27 14:07:23 -08001254 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001255 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001256 }
1257
Jonathan Hart7d656f42015-01-27 14:07:23 -08001258 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001259 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001260 }
1261
Jonathan Hart7d656f42015-01-27 14:07:23 -08001262 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001263 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1264 }
1265
1266 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1267 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001268 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001269 } catch (IOException e) {
1270 log.error("Failed to send" + event + " to " + recipient, e);
1271 }
1272 }
1273
1274 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1275 try {
1276 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1277 } catch (IOException e) {
1278 log.error("Failed to send" + event + " to " + recipient, e);
1279 }
1280 }
1281
1282 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1283 try {
1284 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1285 } catch (IOException e) {
1286 log.error("Failed to send" + event + " to " + recipient, e);
1287 }
1288 }
1289
1290 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1291 try {
1292 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1293 } catch (IOException e) {
1294 log.error("Failed to send" + event + " to " + recipient, e);
1295 }
1296 }
1297
1298 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1299 try {
1300 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1301 } catch (IOException e) {
1302 log.error("Failed to send" + event + " to " + recipient, e);
1303 }
1304 }
1305
1306 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1307 final NodeId self = clusterService.getLocalNode().id();
1308
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001309 final int numDevices = deviceDescs.size();
1310 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1311 final int portsPerDevice = 8; // random factor to minimize reallocation
1312 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1313 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001314
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001315 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001316
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001317 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001318 synchronized (devDescs) {
1319
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001320 // send device offline timestamp
1321 Timestamp lOffline = this.offline.get(deviceId);
1322 if (lOffline != null) {
1323 adOffline.put(deviceId, lOffline);
1324 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001325
1326 for (Entry<ProviderId, DeviceDescriptions>
1327 prov : devDescs.entrySet()) {
1328
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001329 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001330 final ProviderId provId = prov.getKey();
1331 final DeviceDescriptions descs = prov.getValue();
1332
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001333 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001334 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001335
1336 for (Entry<PortNumber, Timestamped<PortDescription>>
1337 portDesc : descs.getPortDescs().entrySet()) {
1338
1339 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001340 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001341 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001342 }
1343 }
1344 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001345 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001346
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001347 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001348 }
1349
1350 /**
1351 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001352 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001353 * Notify sender about out-dated information using regular replication message.
1354 * Send back advertisement to sender if not in sync.
1355 *
1356 * @param advertisement to respond to
1357 */
1358 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1359
1360 final NodeId sender = advertisement.sender();
1361
1362 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1363 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1364 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1365
1366 // Fragments to request
1367 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1368 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1369
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001370 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001371 final DeviceId deviceId = de.getKey();
1372 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1373
1374 synchronized (lDevice) {
1375 // latestTimestamp across provider
1376 // Note: can be null initially
1377 Timestamp localLatest = offline.get(deviceId);
1378
1379 // handle device Ads
1380 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1381 final ProviderId provId = prov.getKey();
1382 final DeviceDescriptions lDeviceDescs = prov.getValue();
1383
1384 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1385
1386
1387 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1388 Timestamp advDevTimestamp = devAds.get(devFragId);
1389
Jonathan Hart403ea932015-02-20 16:23:00 -08001390 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1391 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001392 // remote does not have it or outdated, suggest
1393 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1394 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1395 // local is outdated, request
1396 reqDevices.add(devFragId);
1397 }
1398
1399 // handle port Ads
1400 for (Entry<PortNumber, Timestamped<PortDescription>>
1401 pe : lDeviceDescs.getPortDescs().entrySet()) {
1402
1403 final PortNumber num = pe.getKey();
1404 final Timestamped<PortDescription> lPort = pe.getValue();
1405
1406 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1407
1408 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001409 if (advPortTimestamp == null || lPort.isNewerThan(
1410 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001411 // remote does not have it or outdated, suggest
1412 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1413 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1414 // local is outdated, request
1415 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1416 reqPorts.add(portFragId);
1417 }
1418
1419 // remove port Ad already processed
1420 portAds.remove(portFragId);
1421 } // end local port loop
1422
1423 // remove device Ad already processed
1424 devAds.remove(devFragId);
1425
1426 // find latest and update
1427 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1428 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001429 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001430 localLatest = providerLatest;
1431 }
1432 } // end local provider loop
1433
1434 // checking if remote timestamp is more recent.
1435 Timestamp rOffline = offlineAds.get(deviceId);
1436 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001437 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001438 // remote offline timestamp suggests that the
1439 // device is off-line
1440 markOfflineInternal(deviceId, rOffline);
1441 }
1442
1443 Timestamp lOffline = offline.get(deviceId);
1444 if (lOffline != null && rOffline == null) {
1445 // locally offline, but remote is online, suggest offline
1446 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1447 }
1448
1449 // remove device offline Ad already processed
1450 offlineAds.remove(deviceId);
1451 } // end local device loop
1452 } // device lock
1453
1454 // If there is any Ads left, request them
1455 log.trace("Ads left {}, {}", devAds, portAds);
1456 reqDevices.addAll(devAds.keySet());
1457 reqPorts.addAll(portAds.keySet());
1458
1459 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1460 log.trace("Nothing to request to remote peer {}", sender);
1461 return;
1462 }
1463
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001464 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001465
1466 // 2-way Anti-Entropy for now
1467 try {
1468 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1469 } catch (IOException e) {
1470 log.error("Failed to send response advertisement to " + sender, e);
1471 }
1472
1473// Sketch of 3-way Anti-Entropy
1474// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1475// ClusterMessage message = new ClusterMessage(
1476// clusterService.getLocalNode().id(),
1477// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1478// SERIALIZER.encode(request));
1479//
1480// try {
1481// clusterCommunicator.unicast(message, advertisement.sender());
1482// } catch (IOException e) {
1483// log.error("Failed to send advertisement reply to "
1484// + advertisement.sender(), e);
1485// }
Madan Jampani47c93732014-10-06 20:46:08 -07001486 }
1487
Madan Jampani255a58b2014-10-09 12:08:20 -07001488 private void notifyDelegateIfNotNull(DeviceEvent event) {
1489 if (event != null) {
1490 notifyDelegate(event);
1491 }
1492 }
1493
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001494 private final class SendAdvertisementTask implements Runnable {
1495
1496 @Override
1497 public void run() {
1498 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001499 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001500 return;
1501 }
1502
1503 try {
1504 final NodeId self = clusterService.getLocalNode().id();
1505 Set<ControllerNode> nodes = clusterService.getNodes();
1506
1507 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1508 .transform(toNodeId())
1509 .toList();
1510
1511 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001512 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001513 return;
1514 }
1515
1516 NodeId peer;
1517 do {
1518 int idx = RandomUtils.nextInt(0, nodeIds.size());
1519 peer = nodeIds.get(idx);
1520 } while (peer.equals(self));
1521
1522 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1523
1524 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001525 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001526 return;
1527 }
1528
1529 try {
1530 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1531 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001532 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001533 return;
1534 }
1535 } catch (Exception e) {
1536 // catch all Exception to avoid Scheduled task being suppressed.
1537 log.error("Exception thrown while sending advertisement", e);
1538 }
1539 }
1540 }
1541
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001542 private void handleDeviceEvent(InternalDeviceEvent event) {
1543 ProviderId providerId = event.providerId();
1544 DeviceId deviceId = event.deviceId();
1545 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001546
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001547 try {
1548 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1549 deviceDescription));
1550 } catch (Exception e) {
1551 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001552 }
1553 }
1554
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001555 private void handleDeviceOfflineEvent(InternalDeviceOfflineEvent event) {
1556 DeviceId deviceId = event.deviceId();
1557 Timestamp timestamp = event.timestamp();
Madan Jampani25322532014-10-08 11:20:38 -07001558
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001559 try {
1560 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1561 } catch (Exception e) {
1562 log.warn("Exception thrown handling device offline", e);
Madan Jampani25322532014-10-08 11:20:38 -07001563 }
1564 }
1565
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001566 private void handleRemoveRequest(DeviceId did) {
1567 try {
1568 removeDevice(did);
1569 } catch (Exception e) {
1570 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001571 }
1572 }
1573
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001574 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1575 DeviceId deviceId = event.deviceId();
1576 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001577
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001578 try {
1579 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1580 } catch (Exception e) {
1581 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001582 }
1583 }
1584
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001585 private void handlePortEvent(InternalPortEvent event) {
1586 ProviderId providerId = event.providerId();
1587 DeviceId deviceId = event.deviceId();
1588 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001589
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001590 if (getDevice(deviceId) == null) {
1591 log.debug("{} not found on this node yet, ignoring.", deviceId);
1592 // Note: dropped information will be recovered by anti-entropy
1593 return;
1594 }
Madan Jampani47c93732014-10-06 20:46:08 -07001595
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001596 try {
1597 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1598 } catch (Exception e) {
1599 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001600 }
1601 }
1602
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001603 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1604 ProviderId providerId = event.providerId();
1605 DeviceId deviceId = event.deviceId();
1606 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001607
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001608 if (getDevice(deviceId) == null) {
1609 log.debug("{} not found on this node yet, ignoring.", deviceId);
1610 // Note: dropped information will be recovered by anti-entropy
1611 return;
1612 }
Madan Jampani47c93732014-10-06 20:46:08 -07001613
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001614 try {
1615 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1616 } catch (Exception e) {
1617 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001618 }
1619 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001620
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001621 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1622 try {
1623 handleAdvertisement(advertisement);
1624 } catch (Exception e) {
1625 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001626 }
1627 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001628
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001629 private class InternalPortStatsListener
1630 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1631 @Override
1632 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1633 if (event.type() == PUT) {
1634 Device device = devices.get(event.key());
1635 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001636 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001637 }
1638 }
1639 }
1640 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001641}