blob: 7f1539d133186a86917b8e83a1fe626b76981de7 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2014-present Open Networking Laboratory
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();
480 if (timestamp.compareTo(lastTimestamp) <= 0) {
481 // outdated event ignore
482 return null;
483 }
484
485 offline.put(deviceId, timestamp);
486
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700487 Device device = devices.get(deviceId);
488 if (device == null) {
489 return null;
490 }
491 boolean removed = availableDevices.remove(deviceId);
492 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700493 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700494 }
495 return null;
496 }
497 }
498
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700499 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700500 public boolean markOnline(DeviceId deviceId) {
501 if (devices.containsKey(deviceId)) {
502 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
503 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
504 synchronized (deviceLock) {
505 if (markOnline(deviceId, timestamp)) {
506 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
507 return true;
508 } else {
509 return false;
510 }
511 }
512 }
513 log.warn("Device {} does not exist in store", deviceId);
514 return false;
515
516 }
517
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700518 /**
519 * Marks the device as available if the given timestamp is not outdated,
520 * compared to the time the device has been marked offline.
521 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700522 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700523 * @param timestamp of the event triggering this change.
524 * @return true if availability change request was accepted and changed the state
525 */
526 // Guarded by deviceDescs value (=Device lock)
527 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
528 // accept on-line if given timestamp is newer than
529 // the latest offline request Timestamp
530 Timestamp offlineTimestamp = offline.get(deviceId);
531 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700532 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700533
534 offline.remove(deviceId);
535 return availableDevices.add(deviceId);
536 }
537 return false;
538 }
539
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700540 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700541 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700542 DeviceId deviceId,
543 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700544
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800545 NodeId localNode = clusterService.getLocalNode().id();
546 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
547 // since it will trigger distributed store read.
548 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
549 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
550 // If we don't care much about topology performance, then it might be OK.
551 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700552
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800553 // Process port update only if we're the master of the device,
554 // otherwise signal the actual master.
555 List<DeviceEvent> deviceEvents = null;
556 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700557
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800558 final Timestamp newTimestamp;
559 try {
560 newTimestamp = deviceClockService.getTimestamp(deviceId);
561 } catch (IllegalStateException e) {
562 log.info("Timestamp was not available for device {}", deviceId);
563 log.debug(" discarding {}", portDescriptions);
564 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700565
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800566 // Possible situation:
567 // Device connected and became master for short period of time,
568 // but lost mastership before this instance had the chance to
569 // retrieve term information.
570
571 // Information dropped here is expected to be recoverable by
572 // device probing after mastership change
573
574 return Collections.emptyList();
575 }
576 log.debug("timestamp for {} {}", deviceId, newTimestamp);
577
578 final Timestamped<List<PortDescription>> timestampedInput
579 = new Timestamped<>(portDescriptions, newTimestamp);
580 final Timestamped<List<PortDescription>> merged;
581
582 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
583
584 synchronized (device) {
585 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
586 final DeviceDescriptions descs = device.get(providerId);
587 List<PortDescription> mergedList =
588 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700589 .transform(input ->
590 // lookup merged port description
591 descs.getPortDesc(input.portNumber()).value()
592 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700593 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800594 }
595
596 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700597 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700598 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800599 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
600 }
601
602 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700603 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700604 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700605
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800606 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700607 }
608
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700609 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700610 DeviceId deviceId,
611 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700612
613 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700614 if (device == null) {
615 log.debug("Device is no longer valid: {}", deviceId);
616 return Collections.emptyList();
617 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700618
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700619 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700620 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
621
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700622 List<DeviceEvent> events = new ArrayList<>();
623 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700624
625 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
626 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700627 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700628 }
629
630 DeviceDescriptions descs = descsMap.get(providerId);
631 // every provider must provide DeviceDescription.
632 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700633 "Device description for Device ID %s from Provider %s was not found",
634 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700635
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700636 Map<PortNumber, Port> ports = getPortMap(deviceId);
637
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700638 final Timestamp newTimestamp = portDescriptions.timestamp();
639
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700640 // Add new ports
641 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700642 for (PortDescription portDescription : portDescriptions.value()) {
643 final PortNumber number = portDescription.portNumber();
644 processed.add(number);
645
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700646 final Port oldPort = ports.get(number);
647 final Port newPort;
648
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700649
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700650 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
651 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700652 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700653 // on new port or valid update
654 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700655 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700656 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700657 newPort = composePort(device, number, descsMap);
658 } else {
659 // outdated event, ignored.
660 continue;
661 }
662
663 events.add(oldPort == null ?
664 createPort(device, newPort, ports) :
665 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700666 }
667
668 events.addAll(pruneOldPorts(device, ports, processed));
669 }
670 return FluentIterable.from(events).filter(notNull()).toList();
671 }
672
673 // Creates a new port based on the port description adds it to the map and
674 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700675 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700676 private DeviceEvent createPort(Device device, Port newPort,
677 Map<PortNumber, Port> ports) {
678 ports.put(newPort.number(), newPort);
679 return new DeviceEvent(PORT_ADDED, device, newPort);
680 }
681
682 // Checks if the specified port requires update and if so, it replaces the
683 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700684 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700685 private DeviceEvent updatePort(Device device, Port oldPort,
686 Port newPort,
687 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100688
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700689 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700690 oldPort.type() != newPort.type() ||
691 oldPort.portSpeed() != newPort.portSpeed() ||
692 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700693 ports.put(oldPort.number(), newPort);
694 return new DeviceEvent(PORT_UPDATED, device, newPort);
695 }
696 return null;
697 }
698
Michal Machce774332017-01-25 11:02:55 +0100699 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
700
701 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
702 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
703
704 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
705 }
706
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700707 // Prunes the specified list of ports based on which ports are in the
708 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700709 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700710 private List<DeviceEvent> pruneOldPorts(Device device,
711 Map<PortNumber, Port> ports,
712 Set<PortNumber> processed) {
713 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700714 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700715 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700716 Entry<PortNumber, Port> e = iterator.next();
717 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700718 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700719 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700720 iterator.remove();
721 }
722 }
723 return events;
724 }
725
726 // Gets the map of ports for the specified device; if one does not already
727 // exist, it creates and registers a new one.
728 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700729 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700730 }
731
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700732 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700733 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700734 Map<ProviderId, DeviceDescriptions> r;
735 r = deviceDescs.get(deviceId);
736 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700737 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700738 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
739 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
740 if (concurrentlyAdded != null) {
741 r = concurrentlyAdded;
742 }
743 }
744 return r;
745 }
746
747 // Guarded by deviceDescs value (=Device lock)
748 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
749 Map<ProviderId, DeviceDescriptions> device,
750 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700751 synchronized (device) {
752 DeviceDescriptions r = device.get(providerId);
753 if (r == null) {
754 r = new DeviceDescriptions(deltaDesc);
755 device.put(providerId, r);
756 }
757 return r;
758 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700759 }
760
761 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700762 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
763 DeviceId deviceId,
764 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700765 final Timestamp newTimestamp;
766 try {
767 newTimestamp = deviceClockService.getTimestamp(deviceId);
768 } catch (IllegalStateException e) {
769 log.info("Timestamp was not available for device {}", deviceId);
770 log.debug(" discarding {}", portDescription);
771 // Failed to generate timestamp. Ignoring.
772 // See updatePorts comment
773 return null;
774 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700775 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700776 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700777 final DeviceEvent event;
778 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800779 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
780 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700781 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800782 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700783 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700784 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700785 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700786 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700787 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800788 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700789 }
790 return event;
791 }
792
793 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700794 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700795 Device device = devices.get(deviceId);
796 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
797
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700798 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700799 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
800
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700801 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700802
803 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
804 log.debug("Ignoring outdated event: {}", deltaDesc);
805 return null;
806 }
807
808 DeviceDescriptions descs = descsMap.get(providerId);
809 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700810 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700811 "Device description for Device ID %s from Provider %s was not found",
812 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700813
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700814 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
815 final PortNumber number = deltaDesc.value().portNumber();
816 final Port oldPort = ports.get(number);
817 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700818 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100819 boolean toDelete = false;
820
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700821 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700822 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700823 // on new port or valid update
824 // update description
825 descs.putPortDesc(deltaDesc);
826 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100827 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700828 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700829 // same or outdated event, ignored.
830 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700831 return null;
832 }
833
834 if (oldPort == null) {
835 return createPort(device, newPort, ports);
836 } else {
Michal Machce774332017-01-25 11:02:55 +0100837 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700838 }
839 }
840 }
841
842 @Override
843 public List<Port> getPorts(DeviceId deviceId) {
844 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
845 if (ports == null) {
846 return Collections.emptyList();
847 }
848 return ImmutableList.copyOf(ports.values());
849 }
850
851 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700852 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
853 DeviceId deviceId) {
854 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
855 if (descs == null) {
856 return null;
857 }
858 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
859 final Optional<DeviceDescriptions> devDescs;
860 synchronized (descs) {
861 devDescs = Optional.ofNullable(descs.get(pid));
862 }
863 // DeviceDescriptions is concurrent access-safe
864 return devDescs
865 .map(dd -> dd.getPortDescs().values().stream()
866 .map(Timestamped::value))
867 .orElse(Stream.empty());
868 }
869
870 @Override
sangho538108b2015-04-08 14:29:20 -0700871 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200872 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700873
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200874 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
875 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
876 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
877
878 if (prvStatsMap != null) {
879 for (PortStatistics newStats : newStatsCollection) {
880 PortNumber port = PortNumber.portNumber(newStats.port());
881 PortStatistics prvStats = prvStatsMap.get(port);
882 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
883 PortStatistics deltaStats = builder.build();
884 if (prvStats != null) {
885 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
886 }
887 deltaStatsMap.put(port, deltaStats);
888 newStatsMap.put(port, newStats);
889 }
890 } else {
891 for (PortStatistics newStats : newStatsCollection) {
892 PortNumber port = PortNumber.portNumber(newStats.port());
893 newStatsMap.put(port, newStats);
894 }
sangho538108b2015-04-08 14:29:20 -0700895 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200896 devicePortDeltaStats.put(deviceId, deltaStatsMap);
897 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200898 // DeviceEvent returns null because of InternalPortStatsListener usage
899 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200900 }
901
902 /**
903 * Calculate delta statistics by subtracting previous from new statistics.
904 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700905 * @param deviceId device identifier
906 * @param prvStats previous port statistics
907 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200908 * @return PortStatistics
909 */
910 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
911 // calculate time difference
912 long deltaStatsSec, deltaStatsNano;
913 if (newStats.durationNano() < prvStats.durationNano()) {
914 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
915 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
916 } else {
917 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
918 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
919 }
920 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
921 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
922 .setPort(newStats.port())
923 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
924 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
925 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
926 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
927 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
928 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
929 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
930 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
931 .setDurationSec(deltaStatsSec)
932 .setDurationNano(deltaStatsNano)
933 .build();
934 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700935 }
936
937 @Override
938 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700939 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
940 if (portStats == null) {
941 return Collections.emptyList();
942 }
943 return ImmutableList.copyOf(portStats.values());
944 }
945
946 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530947 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
948 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
949 if (portStatsMap == null) {
950 return null;
951 }
952 PortStatistics portStats = portStatsMap.get(portNumber);
953 return portStats;
954 }
955
956 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200957 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
958 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
959 if (portStats == null) {
960 return Collections.emptyList();
961 }
962 return ImmutableList.copyOf(portStats.values());
963 }
964
965 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530966 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
967 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
968 if (portStatsMap == null) {
969 return null;
970 }
971 PortStatistics portStats = portStatsMap.get(portNumber);
972 return portStats;
973 }
974
975 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700976 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
977 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
978 return ports == null ? null : ports.get(portNumber);
979 }
980
981 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700982 public PortDescription getPortDescription(ProviderId pid,
983 DeviceId deviceId,
984 PortNumber portNumber) {
985 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
986 if (descs == null) {
987 return null;
988 }
989 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
990 final Optional<DeviceDescriptions> devDescs;
991 synchronized (descs) {
992 devDescs = Optional.ofNullable(descs.get(pid));
993 }
994 // DeviceDescriptions is concurrent access-safe
995 return devDescs
996 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
997 .map(Timestamped::value)
998 .orElse(null);
999 }
1000
1001 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001002 public boolean isAvailable(DeviceId deviceId) {
1003 return availableDevices.contains(deviceId);
1004 }
1005
1006 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001007 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001008 final NodeId myId = clusterService.getLocalNode().id();
1009 NodeId master = mastershipService.getMasterFor(deviceId);
1010
1011 // if there exist a master, forward
1012 // if there is no master, try to become one and process
1013
1014 boolean relinquishAtEnd = false;
1015 if (master == null) {
1016 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1017 if (myRole != MastershipRole.NONE) {
1018 relinquishAtEnd = true;
1019 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001020 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001021 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001022 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -07001023 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001024 master = myId;
1025 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001026 }
1027
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001028 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001029 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001030 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001031
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001032 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001033 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001034 /* error log:
1035 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1036 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001037
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001038 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001039 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001040 }
1041
1042 // I have control..
1043
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -07001044 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001045 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001046 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001047 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001048 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001049 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001050 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001051 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001052 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001053 mastershipService.relinquishMastership(deviceId);
1054 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001055 return event;
1056 }
1057
1058 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
1059 Timestamp timestamp) {
1060
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001061 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001062 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001063 // accept removal request if given timestamp is newer than
1064 // the latest Timestamp from Primary provider
1065 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001066 if (primDescs == null) {
1067 return null;
1068 }
1069
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001070 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
1071 if (timestamp.compareTo(lastTimestamp) <= 0) {
1072 // outdated event ignore
1073 return null;
1074 }
1075 removalRequest.put(deviceId, timestamp);
1076
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001077 Device device = devices.remove(deviceId);
1078 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001079 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1080 if (ports != null) {
1081 ports.clear();
1082 }
1083 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001084 descs.clear();
1085 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001086 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001087 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001088 }
1089
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001090 /**
1091 * Checks if given timestamp is superseded by removal request
1092 * with more recent timestamp.
1093 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001094 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001095 * @param timestampToCheck timestamp of an event to check
1096 * @return true if device is already removed
1097 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001098 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1099 Timestamp removalTimestamp = removalRequest.get(deviceId);
1100 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001101 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001102 // removalRequest is more recent
1103 return true;
1104 }
1105 return false;
1106 }
1107
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001108 /**
1109 * Returns a Device, merging description given from multiple Providers.
1110 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001111 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001112 * @param providerDescs Collection of Descriptions from multiple providers
1113 * @return Device instance
1114 */
1115 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001116 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001117
Thomas Vachuska444eda62014-10-28 13:09:42 -07001118 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001119
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001120 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001121
1122 DeviceDescriptions desc = providerDescs.get(primary);
1123
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001124 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001125 Type type = base.type();
1126 String manufacturer = base.manufacturer();
1127 String hwVersion = base.hwVersion();
1128 String swVersion = base.swVersion();
1129 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001130 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001131 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1132 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001133
1134 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1135 if (e.getKey().equals(primary)) {
1136 continue;
1137 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001138 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001139 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001140 // Currently assuming there will never be a key conflict between
1141 // providers
1142
1143 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001144 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001145 }
1146
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001147 return new DefaultDevice(primary, deviceId, type, manufacturer,
1148 hwVersion, swVersion, serialNumber,
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001149 chassisId, annotations.build());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001150 }
1151
Marc De Leenheer88194c32015-05-29 22:10:59 -07001152 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1153 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001154 return new DefaultPort(device, number, isEnabled, description.type(),
1155 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001156 }
1157
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001158 /**
1159 * Returns a Port, merging description given from multiple Providers.
1160 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001161 * @param device device the port is on
1162 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001163 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001164 * @return Port instance
1165 */
1166 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001167 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001168
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001169 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001170 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001171 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001172 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001173 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001174 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001175 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1176 if (portDesc != null) {
1177 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001178 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001179 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001180 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001181 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001182 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001183 if (e.getKey().equals(primary)) {
1184 continue;
1185 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001186 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001187 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001188 // Currently assuming there will never be a key conflict between
1189 // providers
1190
1191 // annotation merging. not so efficient, should revisit later
1192 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1193 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001194 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1195 continue;
1196 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001197 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001198 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001199 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001200 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001201 }
1202 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001203 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001204 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001205 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001206 PortDescription current = portDesc.value();
1207 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001208 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001209 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001210 }
1211
1212 /**
1213 * @return primary ProviderID, or randomly chosen one if none exists
1214 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001215 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001216 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001217 ProviderId fallBackPrimary = null;
1218 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1219 if (!e.getKey().isAncillary()) {
1220 return e.getKey();
1221 } else if (fallBackPrimary == null) {
1222 // pick randomly as a fallback in case there is no primary
1223 fallBackPrimary = e.getKey();
1224 }
1225 }
1226 return fallBackPrimary;
1227 }
1228
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001229 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001230 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001231 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001232 return providerDescs.get(pid);
1233 }
1234
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001235 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001236 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001237 }
1238
Jonathan Hart7d656f42015-01-27 14:07:23 -08001239 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001240 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001241 }
Madan Jampani47c93732014-10-06 20:46:08 -07001242
Jonathan Hart7d656f42015-01-27 14:07:23 -08001243 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001244 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001245 }
1246
Jonathan Hart7d656f42015-01-27 14:07:23 -08001247 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001248 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001249 }
1250
Jonathan Hart7d656f42015-01-27 14:07:23 -08001251 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001252 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001253 }
1254
Jonathan Hart7d656f42015-01-27 14:07:23 -08001255 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001256 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001257 }
1258
Jonathan Hart7d656f42015-01-27 14:07:23 -08001259 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001260 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1261 }
1262
1263 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1264 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001265 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001266 } catch (IOException e) {
1267 log.error("Failed to send" + event + " to " + recipient, e);
1268 }
1269 }
1270
1271 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1272 try {
1273 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1274 } catch (IOException e) {
1275 log.error("Failed to send" + event + " to " + recipient, e);
1276 }
1277 }
1278
1279 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1280 try {
1281 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1282 } catch (IOException e) {
1283 log.error("Failed to send" + event + " to " + recipient, e);
1284 }
1285 }
1286
1287 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1288 try {
1289 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1290 } catch (IOException e) {
1291 log.error("Failed to send" + event + " to " + recipient, e);
1292 }
1293 }
1294
1295 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1296 try {
1297 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1298 } catch (IOException e) {
1299 log.error("Failed to send" + event + " to " + recipient, e);
1300 }
1301 }
1302
1303 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1304 final NodeId self = clusterService.getLocalNode().id();
1305
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001306 final int numDevices = deviceDescs.size();
1307 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1308 final int portsPerDevice = 8; // random factor to minimize reallocation
1309 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1310 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001311
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001312 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001313
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001314 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001315 synchronized (devDescs) {
1316
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001317 // send device offline timestamp
1318 Timestamp lOffline = this.offline.get(deviceId);
1319 if (lOffline != null) {
1320 adOffline.put(deviceId, lOffline);
1321 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001322
1323 for (Entry<ProviderId, DeviceDescriptions>
1324 prov : devDescs.entrySet()) {
1325
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001326 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001327 final ProviderId provId = prov.getKey();
1328 final DeviceDescriptions descs = prov.getValue();
1329
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001330 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001331 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001332
1333 for (Entry<PortNumber, Timestamped<PortDescription>>
1334 portDesc : descs.getPortDescs().entrySet()) {
1335
1336 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001337 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001338 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001339 }
1340 }
1341 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001342 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001343
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001344 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001345 }
1346
1347 /**
1348 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001349 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001350 * Notify sender about out-dated information using regular replication message.
1351 * Send back advertisement to sender if not in sync.
1352 *
1353 * @param advertisement to respond to
1354 */
1355 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1356
1357 final NodeId sender = advertisement.sender();
1358
1359 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1360 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1361 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1362
1363 // Fragments to request
1364 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1365 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1366
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001367 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001368 final DeviceId deviceId = de.getKey();
1369 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1370
1371 synchronized (lDevice) {
1372 // latestTimestamp across provider
1373 // Note: can be null initially
1374 Timestamp localLatest = offline.get(deviceId);
1375
1376 // handle device Ads
1377 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1378 final ProviderId provId = prov.getKey();
1379 final DeviceDescriptions lDeviceDescs = prov.getValue();
1380
1381 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1382
1383
1384 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1385 Timestamp advDevTimestamp = devAds.get(devFragId);
1386
Jonathan Hart403ea932015-02-20 16:23:00 -08001387 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1388 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001389 // remote does not have it or outdated, suggest
1390 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1391 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1392 // local is outdated, request
1393 reqDevices.add(devFragId);
1394 }
1395
1396 // handle port Ads
1397 for (Entry<PortNumber, Timestamped<PortDescription>>
1398 pe : lDeviceDescs.getPortDescs().entrySet()) {
1399
1400 final PortNumber num = pe.getKey();
1401 final Timestamped<PortDescription> lPort = pe.getValue();
1402
1403 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1404
1405 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001406 if (advPortTimestamp == null || lPort.isNewerThan(
1407 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001408 // remote does not have it or outdated, suggest
1409 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1410 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1411 // local is outdated, request
1412 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1413 reqPorts.add(portFragId);
1414 }
1415
1416 // remove port Ad already processed
1417 portAds.remove(portFragId);
1418 } // end local port loop
1419
1420 // remove device Ad already processed
1421 devAds.remove(devFragId);
1422
1423 // find latest and update
1424 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1425 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001426 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001427 localLatest = providerLatest;
1428 }
1429 } // end local provider loop
1430
1431 // checking if remote timestamp is more recent.
1432 Timestamp rOffline = offlineAds.get(deviceId);
1433 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001434 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001435 // remote offline timestamp suggests that the
1436 // device is off-line
1437 markOfflineInternal(deviceId, rOffline);
1438 }
1439
1440 Timestamp lOffline = offline.get(deviceId);
1441 if (lOffline != null && rOffline == null) {
1442 // locally offline, but remote is online, suggest offline
1443 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1444 }
1445
1446 // remove device offline Ad already processed
1447 offlineAds.remove(deviceId);
1448 } // end local device loop
1449 } // device lock
1450
1451 // If there is any Ads left, request them
1452 log.trace("Ads left {}, {}", devAds, portAds);
1453 reqDevices.addAll(devAds.keySet());
1454 reqPorts.addAll(portAds.keySet());
1455
1456 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1457 log.trace("Nothing to request to remote peer {}", sender);
1458 return;
1459 }
1460
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001461 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001462
1463 // 2-way Anti-Entropy for now
1464 try {
1465 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1466 } catch (IOException e) {
1467 log.error("Failed to send response advertisement to " + sender, e);
1468 }
1469
1470// Sketch of 3-way Anti-Entropy
1471// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1472// ClusterMessage message = new ClusterMessage(
1473// clusterService.getLocalNode().id(),
1474// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1475// SERIALIZER.encode(request));
1476//
1477// try {
1478// clusterCommunicator.unicast(message, advertisement.sender());
1479// } catch (IOException e) {
1480// log.error("Failed to send advertisement reply to "
1481// + advertisement.sender(), e);
1482// }
Madan Jampani47c93732014-10-06 20:46:08 -07001483 }
1484
Madan Jampani255a58b2014-10-09 12:08:20 -07001485 private void notifyDelegateIfNotNull(DeviceEvent event) {
1486 if (event != null) {
1487 notifyDelegate(event);
1488 }
1489 }
1490
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001491 private final class SendAdvertisementTask implements Runnable {
1492
1493 @Override
1494 public void run() {
1495 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001496 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001497 return;
1498 }
1499
1500 try {
1501 final NodeId self = clusterService.getLocalNode().id();
1502 Set<ControllerNode> nodes = clusterService.getNodes();
1503
1504 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1505 .transform(toNodeId())
1506 .toList();
1507
1508 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001509 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001510 return;
1511 }
1512
1513 NodeId peer;
1514 do {
1515 int idx = RandomUtils.nextInt(0, nodeIds.size());
1516 peer = nodeIds.get(idx);
1517 } while (peer.equals(self));
1518
1519 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1520
1521 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001522 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001523 return;
1524 }
1525
1526 try {
1527 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1528 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001529 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001530 return;
1531 }
1532 } catch (Exception e) {
1533 // catch all Exception to avoid Scheduled task being suppressed.
1534 log.error("Exception thrown while sending advertisement", e);
1535 }
1536 }
1537 }
1538
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001539 private void handleDeviceEvent(InternalDeviceEvent event) {
1540 ProviderId providerId = event.providerId();
1541 DeviceId deviceId = event.deviceId();
1542 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001543
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001544 try {
1545 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1546 deviceDescription));
1547 } catch (Exception e) {
1548 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001549 }
1550 }
1551
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001552 private void handleDeviceOfflineEvent(InternalDeviceOfflineEvent event) {
1553 DeviceId deviceId = event.deviceId();
1554 Timestamp timestamp = event.timestamp();
Madan Jampani25322532014-10-08 11:20:38 -07001555
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001556 try {
1557 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1558 } catch (Exception e) {
1559 log.warn("Exception thrown handling device offline", e);
Madan Jampani25322532014-10-08 11:20:38 -07001560 }
1561 }
1562
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001563 private void handleRemoveRequest(DeviceId did) {
1564 try {
1565 removeDevice(did);
1566 } catch (Exception e) {
1567 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001568 }
1569 }
1570
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001571 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1572 DeviceId deviceId = event.deviceId();
1573 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001574
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001575 try {
1576 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1577 } catch (Exception e) {
1578 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001579 }
1580 }
1581
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001582 private void handlePortEvent(InternalPortEvent event) {
1583 ProviderId providerId = event.providerId();
1584 DeviceId deviceId = event.deviceId();
1585 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001586
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001587 if (getDevice(deviceId) == null) {
1588 log.debug("{} not found on this node yet, ignoring.", deviceId);
1589 // Note: dropped information will be recovered by anti-entropy
1590 return;
1591 }
Madan Jampani47c93732014-10-06 20:46:08 -07001592
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001593 try {
1594 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1595 } catch (Exception e) {
1596 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001597 }
1598 }
1599
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001600 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1601 ProviderId providerId = event.providerId();
1602 DeviceId deviceId = event.deviceId();
1603 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001604
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001605 if (getDevice(deviceId) == null) {
1606 log.debug("{} not found on this node yet, ignoring.", deviceId);
1607 // Note: dropped information will be recovered by anti-entropy
1608 return;
1609 }
Madan Jampani47c93732014-10-06 20:46:08 -07001610
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001611 try {
1612 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1613 } catch (Exception e) {
1614 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001615 }
1616 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001617
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001618 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1619 try {
1620 handleAdvertisement(advertisement);
1621 } catch (Exception e) {
1622 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001623 }
1624 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001625
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001626 private class InternalPortStatsListener
1627 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1628 @Override
1629 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1630 if (event.type() == PUT) {
1631 Device device = devices.get(event.key());
1632 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001633 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001634 }
1635 }
1636 }
1637 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001638}