blob: 9bfdc1f3c3f4bc328dd413815fff56018a047f86 [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
279 public Iterable<Device> getDevices() {
280 return Collections.unmodifiableCollection(devices.values());
281 }
282
283 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800284 public Iterable<Device> getAvailableDevices() {
285 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700286 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800287 }
288
289 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700290 public Device getDevice(DeviceId deviceId) {
291 return devices.get(deviceId);
292 }
293
294 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700295 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700296 DeviceId deviceId,
297 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800298 NodeId localNode = clusterService.getLocalNode().id();
299 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
300
301 // Process device update only if we're the master,
302 // otherwise signal the actual master.
303 DeviceEvent deviceEvent = null;
304 if (localNode.equals(deviceNode)) {
305
306 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
307 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
308 final Timestamped<DeviceDescription> mergedDesc;
309 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
310
311 synchronized (device) {
312 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
313 mergedDesc = device.get(providerId).getDeviceDesc();
314 }
315
316 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700317 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
helenyrwufd296b62016-06-22 17:43:02 -0700318 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800319 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
320 }
321
322 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700323 return null;
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700324 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800325
326 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700327 }
328
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700329 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700330 DeviceId deviceId,
331 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700332
333 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800334 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700335 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700336
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800337 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700338 // locking per device
339
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700340 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
341 log.debug("Ignoring outdated event: {}", deltaDesc);
342 return null;
343 }
344
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800345 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700346
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700347 final Device oldDevice = devices.get(deviceId);
348 final Device newDevice;
349
350 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700351 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700352 // on new device or valid update
353 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800354 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700355 } else {
356 // outdated event, ignored.
357 return null;
358 }
359 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700360 // REGISTER
361 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700362 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700363 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700364 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700365 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700366 } else {
367 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700368 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
369 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700370 }
371 }
372 }
373
374 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700375 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700376 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700377 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700378
379 // update composed device cache
380 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
381 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700382 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
383 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700384
385 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700386 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700387 }
388
389 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
390 }
391
392 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700393 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700394 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700395 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700396 Device newDevice, Timestamp newTimestamp,
397 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700398 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700399 boolean propertiesChanged =
400 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700401 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
402 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700403 boolean annotationsChanged =
404 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700405
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700406 // Primary providers can respond to all changes, but ancillary ones
407 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800408 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700409 if ((providerId.isAncillary() && annotationsChanged) ||
410 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700411 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
412 if (!replaced) {
413 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700414 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800415 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700416 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700417
alshabibdc5d8bd2015-11-02 15:41:29 -0800418 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700419 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800420
helenyrwufd296b62016-06-22 17:43:02 -0700421 if (!providerId.isAncillary() && forceAvailable) {
alshabibdc5d8bd2015-11-02 15:41:29 -0800422 boolean wasOnline = availableDevices.contains(newDevice.id());
423 markOnline(newDevice.id(), newTimestamp);
424 if (!wasOnline) {
425 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
426 }
427 }
428 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700429 }
430
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700431 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700432 // update composed device cache
433 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
434 verify(oldDevice == null,
435 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
436 providerId, oldDevice, newDevice);
437
438 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700439 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700440 }
441
442 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
443 }
444
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700445 @Override
446 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700447 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
448 }
449
450 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700451 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700452 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700453 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700454 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800455 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700456 }
457 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700458 }
459
460 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700461 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700462 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700463
464 // locking device
465 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700466 // accept off-line if given timestamp is newer than
467 // the latest Timestamp from Primary provider
468 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
Thomas Vachuska4bd10b92016-12-15 10:13:38 -0800469 if (primDescs == null) {
470 return null;
471 }
472
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700473 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
474 if (timestamp.compareTo(lastTimestamp) <= 0) {
475 // outdated event ignore
476 return null;
477 }
478
479 offline.put(deviceId, timestamp);
480
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700481 Device device = devices.get(deviceId);
482 if (device == null) {
483 return null;
484 }
485 boolean removed = availableDevices.remove(deviceId);
486 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700487 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700488 }
489 return null;
490 }
491 }
492
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700493 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700494 public boolean markOnline(DeviceId deviceId) {
495 if (devices.containsKey(deviceId)) {
496 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
497 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
498 synchronized (deviceLock) {
499 if (markOnline(deviceId, timestamp)) {
500 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
501 return true;
502 } else {
503 return false;
504 }
505 }
506 }
507 log.warn("Device {} does not exist in store", deviceId);
508 return false;
509
510 }
511
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700512 /**
513 * Marks the device as available if the given timestamp is not outdated,
514 * compared to the time the device has been marked offline.
515 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700516 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700517 * @param timestamp of the event triggering this change.
518 * @return true if availability change request was accepted and changed the state
519 */
520 // Guarded by deviceDescs value (=Device lock)
521 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
522 // accept on-line if given timestamp is newer than
523 // the latest offline request Timestamp
524 Timestamp offlineTimestamp = offline.get(deviceId);
525 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700526 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700527
528 offline.remove(deviceId);
529 return availableDevices.add(deviceId);
530 }
531 return false;
532 }
533
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700534 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700535 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700536 DeviceId deviceId,
537 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700538
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800539 NodeId localNode = clusterService.getLocalNode().id();
540 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
541 // since it will trigger distributed store read.
542 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
543 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
544 // If we don't care much about topology performance, then it might be OK.
545 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700546
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800547 // Process port update only if we're the master of the device,
548 // otherwise signal the actual master.
549 List<DeviceEvent> deviceEvents = null;
550 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700551
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800552 final Timestamp newTimestamp;
553 try {
554 newTimestamp = deviceClockService.getTimestamp(deviceId);
555 } catch (IllegalStateException e) {
556 log.info("Timestamp was not available for device {}", deviceId);
557 log.debug(" discarding {}", portDescriptions);
558 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700559
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800560 // Possible situation:
561 // Device connected and became master for short period of time,
562 // but lost mastership before this instance had the chance to
563 // retrieve term information.
564
565 // Information dropped here is expected to be recoverable by
566 // device probing after mastership change
567
568 return Collections.emptyList();
569 }
570 log.debug("timestamp for {} {}", deviceId, newTimestamp);
571
572 final Timestamped<List<PortDescription>> timestampedInput
573 = new Timestamped<>(portDescriptions, newTimestamp);
574 final Timestamped<List<PortDescription>> merged;
575
576 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
577
578 synchronized (device) {
579 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
580 final DeviceDescriptions descs = device.get(providerId);
581 List<PortDescription> mergedList =
582 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700583 .transform(input ->
584 // lookup merged port description
585 descs.getPortDesc(input.portNumber()).value()
586 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700587 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800588 }
589
590 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700591 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700592 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800593 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
594 }
595
596 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700597 return Collections.emptyList();
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700598 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700599
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800600 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700601 }
602
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700603 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700604 DeviceId deviceId,
605 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700606
607 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700608 if (device == null) {
609 log.debug("Device is no longer valid: {}", deviceId);
610 return Collections.emptyList();
611 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700612
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700613 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700614 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
615
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700616 List<DeviceEvent> events = new ArrayList<>();
617 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700618
619 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
620 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700621 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700622 }
623
624 DeviceDescriptions descs = descsMap.get(providerId);
625 // every provider must provide DeviceDescription.
626 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700627 "Device description for Device ID %s from Provider %s was not found",
628 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700629
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700630 Map<PortNumber, Port> ports = getPortMap(deviceId);
631
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700632 final Timestamp newTimestamp = portDescriptions.timestamp();
633
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700634 // Add new ports
635 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700636 for (PortDescription portDescription : portDescriptions.value()) {
637 final PortNumber number = portDescription.portNumber();
638 processed.add(number);
639
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700640 final Port oldPort = ports.get(number);
641 final Port newPort;
642
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700643
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700644 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
645 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700646 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700647 // on new port or valid update
648 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700649 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700650 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700651 newPort = composePort(device, number, descsMap);
652 } else {
653 // outdated event, ignored.
654 continue;
655 }
656
657 events.add(oldPort == null ?
658 createPort(device, newPort, ports) :
659 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700660 }
661
662 events.addAll(pruneOldPorts(device, ports, processed));
663 }
664 return FluentIterable.from(events).filter(notNull()).toList();
665 }
666
667 // Creates a new port based on the port description adds it to the map and
668 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700669 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700670 private DeviceEvent createPort(Device device, Port newPort,
671 Map<PortNumber, Port> ports) {
672 ports.put(newPort.number(), newPort);
673 return new DeviceEvent(PORT_ADDED, device, newPort);
674 }
675
676 // Checks if the specified port requires update and if so, it replaces the
677 // existing entry in the map and 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 updatePort(Device device, Port oldPort,
680 Port newPort,
681 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100682
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700683 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700684 oldPort.type() != newPort.type() ||
685 oldPort.portSpeed() != newPort.portSpeed() ||
686 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700687 ports.put(oldPort.number(), newPort);
688 return new DeviceEvent(PORT_UPDATED, device, newPort);
689 }
690 return null;
691 }
692
Michal Machce774332017-01-25 11:02:55 +0100693 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
694
695 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
696 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
697
698 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
699 }
700
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700701 // Prunes the specified list of ports based on which ports are in the
702 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700703 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700704 private List<DeviceEvent> pruneOldPorts(Device device,
705 Map<PortNumber, Port> ports,
706 Set<PortNumber> processed) {
707 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700708 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700709 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700710 Entry<PortNumber, Port> e = iterator.next();
711 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700712 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700713 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700714 iterator.remove();
715 }
716 }
717 return events;
718 }
719
720 // Gets the map of ports for the specified device; if one does not already
721 // exist, it creates and registers a new one.
722 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700723 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700724 }
725
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700726 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700727 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700728 Map<ProviderId, DeviceDescriptions> r;
729 r = deviceDescs.get(deviceId);
730 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700731 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700732 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
733 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
734 if (concurrentlyAdded != null) {
735 r = concurrentlyAdded;
736 }
737 }
738 return r;
739 }
740
741 // Guarded by deviceDescs value (=Device lock)
742 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
743 Map<ProviderId, DeviceDescriptions> device,
744 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700745 synchronized (device) {
746 DeviceDescriptions r = device.get(providerId);
747 if (r == null) {
748 r = new DeviceDescriptions(deltaDesc);
749 device.put(providerId, r);
750 }
751 return r;
752 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700753 }
754
755 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700756 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
757 DeviceId deviceId,
758 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700759 final Timestamp newTimestamp;
760 try {
761 newTimestamp = deviceClockService.getTimestamp(deviceId);
762 } catch (IllegalStateException e) {
763 log.info("Timestamp was not available for device {}", deviceId);
764 log.debug(" discarding {}", portDescription);
765 // Failed to generate timestamp. Ignoring.
766 // See updatePorts comment
767 return null;
768 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700769 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700770 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700771 final DeviceEvent event;
772 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800773 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
774 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700775 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800776 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700777 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700778 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700779 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700780 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700781 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800782 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700783 }
784 return event;
785 }
786
787 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700788 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700789 Device device = devices.get(deviceId);
790 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
791
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700792 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700793 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
794
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700795 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700796
797 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
798 log.debug("Ignoring outdated event: {}", deltaDesc);
799 return null;
800 }
801
802 DeviceDescriptions descs = descsMap.get(providerId);
803 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700804 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700805 "Device description for Device ID %s from Provider %s was not found",
806 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700807
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700808 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
809 final PortNumber number = deltaDesc.value().portNumber();
810 final Port oldPort = ports.get(number);
811 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700812 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100813 boolean toDelete = false;
814
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700815 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700816 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700817 // on new port or valid update
818 // update description
819 descs.putPortDesc(deltaDesc);
820 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100821 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700822 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700823 // same or outdated event, ignored.
824 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700825 return null;
826 }
827
828 if (oldPort == null) {
829 return createPort(device, newPort, ports);
830 } else {
Michal Machce774332017-01-25 11:02:55 +0100831 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700832 }
833 }
834 }
835
836 @Override
837 public List<Port> getPorts(DeviceId deviceId) {
838 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
839 if (ports == null) {
840 return Collections.emptyList();
841 }
842 return ImmutableList.copyOf(ports.values());
843 }
844
845 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700846 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
847 DeviceId deviceId) {
848 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
849 if (descs == null) {
850 return null;
851 }
852 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
853 final Optional<DeviceDescriptions> devDescs;
854 synchronized (descs) {
855 devDescs = Optional.ofNullable(descs.get(pid));
856 }
857 // DeviceDescriptions is concurrent access-safe
858 return devDescs
859 .map(dd -> dd.getPortDescs().values().stream()
860 .map(Timestamped::value))
861 .orElse(Stream.empty());
862 }
863
864 @Override
sangho538108b2015-04-08 14:29:20 -0700865 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200866 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700867
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200868 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
869 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
870 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
871
872 if (prvStatsMap != null) {
873 for (PortStatistics newStats : newStatsCollection) {
874 PortNumber port = PortNumber.portNumber(newStats.port());
875 PortStatistics prvStats = prvStatsMap.get(port);
876 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
877 PortStatistics deltaStats = builder.build();
878 if (prvStats != null) {
879 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
880 }
881 deltaStatsMap.put(port, deltaStats);
882 newStatsMap.put(port, newStats);
883 }
884 } else {
885 for (PortStatistics newStats : newStatsCollection) {
886 PortNumber port = PortNumber.portNumber(newStats.port());
887 newStatsMap.put(port, newStats);
888 }
sangho538108b2015-04-08 14:29:20 -0700889 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200890 devicePortDeltaStats.put(deviceId, deltaStatsMap);
891 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200892 // DeviceEvent returns null because of InternalPortStatsListener usage
893 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200894 }
895
896 /**
897 * Calculate delta statistics by subtracting previous from new statistics.
898 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700899 * @param deviceId device identifier
900 * @param prvStats previous port statistics
901 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200902 * @return PortStatistics
903 */
904 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
905 // calculate time difference
906 long deltaStatsSec, deltaStatsNano;
907 if (newStats.durationNano() < prvStats.durationNano()) {
908 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
909 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
910 } else {
911 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
912 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
913 }
914 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
915 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
916 .setPort(newStats.port())
917 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
918 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
919 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
920 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
921 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
922 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
923 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
924 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
925 .setDurationSec(deltaStatsSec)
926 .setDurationNano(deltaStatsNano)
927 .build();
928 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700929 }
930
931 @Override
932 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700933 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
934 if (portStats == null) {
935 return Collections.emptyList();
936 }
937 return ImmutableList.copyOf(portStats.values());
938 }
939
940 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530941 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
942 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
943 if (portStatsMap == null) {
944 return null;
945 }
946 PortStatistics portStats = portStatsMap.get(portNumber);
947 return portStats;
948 }
949
950 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200951 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
952 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
953 if (portStats == null) {
954 return Collections.emptyList();
955 }
956 return ImmutableList.copyOf(portStats.values());
957 }
958
959 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530960 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
961 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
962 if (portStatsMap == null) {
963 return null;
964 }
965 PortStatistics portStats = portStatsMap.get(portNumber);
966 return portStats;
967 }
968
969 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700970 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
971 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
972 return ports == null ? null : ports.get(portNumber);
973 }
974
975 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700976 public PortDescription getPortDescription(ProviderId pid,
977 DeviceId deviceId,
978 PortNumber portNumber) {
979 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
980 if (descs == null) {
981 return null;
982 }
983 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
984 final Optional<DeviceDescriptions> devDescs;
985 synchronized (descs) {
986 devDescs = Optional.ofNullable(descs.get(pid));
987 }
988 // DeviceDescriptions is concurrent access-safe
989 return devDescs
990 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
991 .map(Timestamped::value)
992 .orElse(null);
993 }
994
995 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700996 public boolean isAvailable(DeviceId deviceId) {
997 return availableDevices.contains(deviceId);
998 }
999
1000 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001001 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001002 final NodeId myId = clusterService.getLocalNode().id();
1003 NodeId master = mastershipService.getMasterFor(deviceId);
1004
1005 // if there exist a master, forward
1006 // if there is no master, try to become one and process
1007
1008 boolean relinquishAtEnd = false;
1009 if (master == null) {
1010 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1011 if (myRole != MastershipRole.NONE) {
1012 relinquishAtEnd = true;
1013 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001014 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001015 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001016 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -07001017 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001018 master = myId;
1019 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001020 }
1021
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001022 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001023 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001024 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001025
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001026 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001027 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001028 /* error log:
1029 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1030 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001031
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001032 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001033 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001034 }
1035
1036 // I have control..
1037
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -07001038 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001039 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001040 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001041 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001042 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001043 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001044 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001045 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001046 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001047 mastershipService.relinquishMastership(deviceId);
1048 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001049 return event;
1050 }
1051
1052 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
1053 Timestamp timestamp) {
1054
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001055 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001056 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001057 // accept removal request if given timestamp is newer than
1058 // the latest Timestamp from Primary provider
1059 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001060 if (primDescs == null) {
1061 return null;
1062 }
1063
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001064 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
1065 if (timestamp.compareTo(lastTimestamp) <= 0) {
1066 // outdated event ignore
1067 return null;
1068 }
1069 removalRequest.put(deviceId, timestamp);
1070
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001071 Device device = devices.remove(deviceId);
1072 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001073 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1074 if (ports != null) {
1075 ports.clear();
1076 }
1077 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001078 descs.clear();
1079 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001080 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001081 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001082 }
1083
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001084 /**
1085 * Checks if given timestamp is superseded by removal request
1086 * with more recent timestamp.
1087 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001088 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001089 * @param timestampToCheck timestamp of an event to check
1090 * @return true if device is already removed
1091 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001092 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1093 Timestamp removalTimestamp = removalRequest.get(deviceId);
1094 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001095 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001096 // removalRequest is more recent
1097 return true;
1098 }
1099 return false;
1100 }
1101
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001102 /**
1103 * Returns a Device, merging description given from multiple Providers.
1104 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001105 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001106 * @param providerDescs Collection of Descriptions from multiple providers
1107 * @return Device instance
1108 */
1109 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001110 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001111
Thomas Vachuska444eda62014-10-28 13:09:42 -07001112 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001113
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001114 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001115
1116 DeviceDescriptions desc = providerDescs.get(primary);
1117
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001118 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001119 Type type = base.type();
1120 String manufacturer = base.manufacturer();
1121 String hwVersion = base.hwVersion();
1122 String swVersion = base.swVersion();
1123 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001124 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001125 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
1126 annotations.putAll(base.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001127
1128 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1129 if (e.getKey().equals(primary)) {
1130 continue;
1131 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001132 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001133 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001134 // Currently assuming there will never be a key conflict between
1135 // providers
1136
1137 // annotation merging. not so efficient, should revisit later
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001138 annotations.putAll(e.getValue().getDeviceDesc().value().annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001139 }
1140
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001141 return new DefaultDevice(primary, deviceId, type, manufacturer,
1142 hwVersion, swVersion, serialNumber,
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001143 chassisId, annotations.build());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001144 }
1145
Marc De Leenheer88194c32015-05-29 22:10:59 -07001146 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1147 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001148 return new DefaultPort(device, number, isEnabled, description.type(),
1149 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001150 }
1151
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001152 /**
1153 * Returns a Port, merging description given from multiple Providers.
1154 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001155 * @param device device the port is on
1156 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001157 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001158 * @return Port instance
1159 */
1160 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001161 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001162
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001163 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001164 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001165 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001166 boolean isEnabled = false;
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001167 DefaultAnnotations.Builder annotations = DefaultAnnotations.builder();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001168 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001169 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1170 if (portDesc != null) {
1171 isEnabled = portDesc.value().isEnabled();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001172 annotations.putAll(portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001173 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001174 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001175 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001176 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001177 if (e.getKey().equals(primary)) {
1178 continue;
1179 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001180 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001181 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001182 // Currently assuming there will never be a key conflict between
1183 // providers
1184
1185 // annotation merging. not so efficient, should revisit later
1186 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1187 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001188 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1189 continue;
1190 }
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001191 annotations.putAll(otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001192 PortDescription other = otherPortDesc.value();
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001193 updated = buildTypedPort(device, number, isEnabled, other, annotations.build());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001194 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001195 }
1196 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001197 if (portDesc == null) {
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001198 return updated == null ? new DefaultPort(device, number, false, annotations.build()) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001199 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001200 PortDescription current = portDesc.value();
1201 return updated == null
Yuta HIGUCHI9eed0b12017-06-07 11:59:18 -07001202 ? buildTypedPort(device, number, isEnabled, current, annotations.build())
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001203 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001204 }
1205
1206 /**
1207 * @return primary ProviderID, or randomly chosen one if none exists
1208 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001209 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001210 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001211 ProviderId fallBackPrimary = null;
1212 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1213 if (!e.getKey().isAncillary()) {
1214 return e.getKey();
1215 } else if (fallBackPrimary == null) {
1216 // pick randomly as a fallback in case there is no primary
1217 fallBackPrimary = e.getKey();
1218 }
1219 }
1220 return fallBackPrimary;
1221 }
1222
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001223 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001224 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001225 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001226 return providerDescs.get(pid);
1227 }
1228
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001229 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001230 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001231 }
1232
Jonathan Hart7d656f42015-01-27 14:07:23 -08001233 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001234 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001235 }
Madan Jampani47c93732014-10-06 20:46:08 -07001236
Jonathan Hart7d656f42015-01-27 14:07:23 -08001237 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001238 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001239 }
1240
Jonathan Hart7d656f42015-01-27 14:07:23 -08001241 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001242 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001243 }
1244
Jonathan Hart7d656f42015-01-27 14:07:23 -08001245 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001246 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001247 }
1248
Jonathan Hart7d656f42015-01-27 14:07:23 -08001249 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001250 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001251 }
1252
Jonathan Hart7d656f42015-01-27 14:07:23 -08001253 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001254 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1255 }
1256
1257 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1258 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001259 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001260 } catch (IOException e) {
1261 log.error("Failed to send" + event + " to " + recipient, e);
1262 }
1263 }
1264
1265 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1266 try {
1267 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1268 } catch (IOException e) {
1269 log.error("Failed to send" + event + " to " + recipient, e);
1270 }
1271 }
1272
1273 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1274 try {
1275 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1276 } catch (IOException e) {
1277 log.error("Failed to send" + event + " to " + recipient, e);
1278 }
1279 }
1280
1281 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1282 try {
1283 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1284 } catch (IOException e) {
1285 log.error("Failed to send" + event + " to " + recipient, e);
1286 }
1287 }
1288
1289 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1290 try {
1291 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1292 } catch (IOException e) {
1293 log.error("Failed to send" + event + " to " + recipient, e);
1294 }
1295 }
1296
1297 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1298 final NodeId self = clusterService.getLocalNode().id();
1299
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001300 final int numDevices = deviceDescs.size();
1301 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1302 final int portsPerDevice = 8; // random factor to minimize reallocation
1303 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1304 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001305
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001306 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001307
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001308 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001309 synchronized (devDescs) {
1310
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001311 // send device offline timestamp
1312 Timestamp lOffline = this.offline.get(deviceId);
1313 if (lOffline != null) {
1314 adOffline.put(deviceId, lOffline);
1315 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001316
1317 for (Entry<ProviderId, DeviceDescriptions>
1318 prov : devDescs.entrySet()) {
1319
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001320 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001321 final ProviderId provId = prov.getKey();
1322 final DeviceDescriptions descs = prov.getValue();
1323
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001324 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001325 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001326
1327 for (Entry<PortNumber, Timestamped<PortDescription>>
1328 portDesc : descs.getPortDescs().entrySet()) {
1329
1330 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001331 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001332 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001333 }
1334 }
1335 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001336 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001337
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001338 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001339 }
1340
1341 /**
1342 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001343 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001344 * Notify sender about out-dated information using regular replication message.
1345 * Send back advertisement to sender if not in sync.
1346 *
1347 * @param advertisement to respond to
1348 */
1349 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1350
1351 final NodeId sender = advertisement.sender();
1352
1353 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1354 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1355 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1356
1357 // Fragments to request
1358 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1359 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1360
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001361 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001362 final DeviceId deviceId = de.getKey();
1363 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1364
1365 synchronized (lDevice) {
1366 // latestTimestamp across provider
1367 // Note: can be null initially
1368 Timestamp localLatest = offline.get(deviceId);
1369
1370 // handle device Ads
1371 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1372 final ProviderId provId = prov.getKey();
1373 final DeviceDescriptions lDeviceDescs = prov.getValue();
1374
1375 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1376
1377
1378 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1379 Timestamp advDevTimestamp = devAds.get(devFragId);
1380
Jonathan Hart403ea932015-02-20 16:23:00 -08001381 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1382 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001383 // remote does not have it or outdated, suggest
1384 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1385 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1386 // local is outdated, request
1387 reqDevices.add(devFragId);
1388 }
1389
1390 // handle port Ads
1391 for (Entry<PortNumber, Timestamped<PortDescription>>
1392 pe : lDeviceDescs.getPortDescs().entrySet()) {
1393
1394 final PortNumber num = pe.getKey();
1395 final Timestamped<PortDescription> lPort = pe.getValue();
1396
1397 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1398
1399 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001400 if (advPortTimestamp == null || lPort.isNewerThan(
1401 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001402 // remote does not have it or outdated, suggest
1403 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1404 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1405 // local is outdated, request
1406 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1407 reqPorts.add(portFragId);
1408 }
1409
1410 // remove port Ad already processed
1411 portAds.remove(portFragId);
1412 } // end local port loop
1413
1414 // remove device Ad already processed
1415 devAds.remove(devFragId);
1416
1417 // find latest and update
1418 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1419 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001420 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001421 localLatest = providerLatest;
1422 }
1423 } // end local provider loop
1424
1425 // checking if remote timestamp is more recent.
1426 Timestamp rOffline = offlineAds.get(deviceId);
1427 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001428 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001429 // remote offline timestamp suggests that the
1430 // device is off-line
1431 markOfflineInternal(deviceId, rOffline);
1432 }
1433
1434 Timestamp lOffline = offline.get(deviceId);
1435 if (lOffline != null && rOffline == null) {
1436 // locally offline, but remote is online, suggest offline
1437 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1438 }
1439
1440 // remove device offline Ad already processed
1441 offlineAds.remove(deviceId);
1442 } // end local device loop
1443 } // device lock
1444
1445 // If there is any Ads left, request them
1446 log.trace("Ads left {}, {}", devAds, portAds);
1447 reqDevices.addAll(devAds.keySet());
1448 reqPorts.addAll(portAds.keySet());
1449
1450 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1451 log.trace("Nothing to request to remote peer {}", sender);
1452 return;
1453 }
1454
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001455 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001456
1457 // 2-way Anti-Entropy for now
1458 try {
1459 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1460 } catch (IOException e) {
1461 log.error("Failed to send response advertisement to " + sender, e);
1462 }
1463
1464// Sketch of 3-way Anti-Entropy
1465// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1466// ClusterMessage message = new ClusterMessage(
1467// clusterService.getLocalNode().id(),
1468// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1469// SERIALIZER.encode(request));
1470//
1471// try {
1472// clusterCommunicator.unicast(message, advertisement.sender());
1473// } catch (IOException e) {
1474// log.error("Failed to send advertisement reply to "
1475// + advertisement.sender(), e);
1476// }
Madan Jampani47c93732014-10-06 20:46:08 -07001477 }
1478
Madan Jampani255a58b2014-10-09 12:08:20 -07001479 private void notifyDelegateIfNotNull(DeviceEvent event) {
1480 if (event != null) {
1481 notifyDelegate(event);
1482 }
1483 }
1484
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001485 private final class SendAdvertisementTask implements Runnable {
1486
1487 @Override
1488 public void run() {
1489 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001490 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001491 return;
1492 }
1493
1494 try {
1495 final NodeId self = clusterService.getLocalNode().id();
1496 Set<ControllerNode> nodes = clusterService.getNodes();
1497
1498 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1499 .transform(toNodeId())
1500 .toList();
1501
1502 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001503 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001504 return;
1505 }
1506
1507 NodeId peer;
1508 do {
1509 int idx = RandomUtils.nextInt(0, nodeIds.size());
1510 peer = nodeIds.get(idx);
1511 } while (peer.equals(self));
1512
1513 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1514
1515 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001516 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001517 return;
1518 }
1519
1520 try {
1521 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1522 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001523 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001524 return;
1525 }
1526 } catch (Exception e) {
1527 // catch all Exception to avoid Scheduled task being suppressed.
1528 log.error("Exception thrown while sending advertisement", e);
1529 }
1530 }
1531 }
1532
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001533 private void handleDeviceEvent(InternalDeviceEvent event) {
1534 ProviderId providerId = event.providerId();
1535 DeviceId deviceId = event.deviceId();
1536 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001537
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001538 try {
1539 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1540 deviceDescription));
1541 } catch (Exception e) {
1542 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001543 }
1544 }
1545
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001546 private void handleDeviceOfflineEvent(InternalDeviceOfflineEvent event) {
1547 DeviceId deviceId = event.deviceId();
1548 Timestamp timestamp = event.timestamp();
Madan Jampani25322532014-10-08 11:20:38 -07001549
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001550 try {
1551 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1552 } catch (Exception e) {
1553 log.warn("Exception thrown handling device offline", e);
Madan Jampani25322532014-10-08 11:20:38 -07001554 }
1555 }
1556
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001557 private void handleRemoveRequest(DeviceId did) {
1558 try {
1559 removeDevice(did);
1560 } catch (Exception e) {
1561 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001562 }
1563 }
1564
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001565 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1566 DeviceId deviceId = event.deviceId();
1567 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001568
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001569 try {
1570 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1571 } catch (Exception e) {
1572 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001573 }
1574 }
1575
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001576 private void handlePortEvent(InternalPortEvent event) {
1577 ProviderId providerId = event.providerId();
1578 DeviceId deviceId = event.deviceId();
1579 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001580
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001581 if (getDevice(deviceId) == null) {
1582 log.debug("{} not found on this node yet, ignoring.", deviceId);
1583 // Note: dropped information will be recovered by anti-entropy
1584 return;
1585 }
Madan Jampani47c93732014-10-06 20:46:08 -07001586
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001587 try {
1588 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1589 } catch (Exception e) {
1590 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001591 }
1592 }
1593
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001594 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1595 ProviderId providerId = event.providerId();
1596 DeviceId deviceId = event.deviceId();
1597 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001598
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001599 if (getDevice(deviceId) == null) {
1600 log.debug("{} not found on this node yet, ignoring.", deviceId);
1601 // Note: dropped information will be recovered by anti-entropy
1602 return;
1603 }
Madan Jampani47c93732014-10-06 20:46:08 -07001604
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001605 try {
1606 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1607 } catch (Exception e) {
1608 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001609 }
1610 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001611
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001612 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1613 try {
1614 handleAdvertisement(advertisement);
1615 } catch (Exception e) {
1616 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001617 }
1618 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001619
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001620 private class InternalPortStatsListener
1621 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1622 @Override
1623 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1624 if (event.type() == PUT) {
1625 Device device = devices.get(event.key());
1626 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001627 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001628 }
1629 }
1630 }
1631 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001632}