blob: 52d0c3c202cc493cc5744e4cbef2edfb1708fbec [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
18import com.google.common.collect.FluentIterable;
19import com.google.common.collect.ImmutableList;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -070020import com.google.common.collect.Maps;
21import com.google.common.collect.Sets;
Dusan Pajin11ff4a82015-08-20 18:03:05 +020022
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070023import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070024import org.apache.felix.scr.annotations.Activate;
25import org.apache.felix.scr.annotations.Component;
26import org.apache.felix.scr.annotations.Deactivate;
27import org.apache.felix.scr.annotations.Reference;
28import org.apache.felix.scr.annotations.ReferenceCardinality;
29import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080030import org.onlab.packet.ChassisId;
31import org.onlab.util.KryoNamespace;
32import org.onlab.util.NewConcurrentHashMap;
Brian O'Connorabafb502014-12-02 22:26:20 -080033import org.onosproject.cluster.ClusterService;
34import org.onosproject.cluster.ControllerNode;
35import org.onosproject.cluster.NodeId;
36import org.onosproject.mastership.MastershipService;
37import org.onosproject.mastership.MastershipTerm;
38import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070039import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.net.AnnotationsUtil;
41import org.onosproject.net.DefaultAnnotations;
42import org.onosproject.net.DefaultDevice;
43import org.onosproject.net.DefaultPort;
44import org.onosproject.net.Device;
45import org.onosproject.net.Device.Type;
46import org.onosproject.net.DeviceId;
47import org.onosproject.net.MastershipRole;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070048import org.onosproject.net.OchPort;
49import org.onosproject.net.OduCltPort;
50import org.onosproject.net.OmsPort;
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +020051import org.onosproject.net.OtuPort;
Brian O'Connorabafb502014-12-02 22:26:20 -080052import org.onosproject.net.Port;
53import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070054import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.net.device.DeviceClockService;
56import org.onosproject.net.device.DeviceDescription;
57import org.onosproject.net.device.DeviceEvent;
58import org.onosproject.net.device.DeviceStore;
59import org.onosproject.net.device.DeviceStoreDelegate;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070060import org.onosproject.net.device.OchPortDescription;
61import org.onosproject.net.device.OduCltPortDescription;
62import org.onosproject.net.device.OmsPortDescription;
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +020063import org.onosproject.net.device.OtuPortDescription;
Brian O'Connorabafb502014-12-02 22:26:20 -080064import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070065import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080066import org.onosproject.net.provider.ProviderId;
67import org.onosproject.store.AbstractStore;
68import org.onosproject.store.Timestamp;
69import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
70import org.onosproject.store.cluster.messaging.ClusterMessage;
71import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
72import org.onosproject.store.cluster.messaging.MessageSubject;
73import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070074import org.onosproject.store.serializers.KryoNamespaces;
HIGUCHI Yutae7290652016-05-18 11:29:01 -070075import org.onosproject.store.serializers.StoreSerializer;
Brian O'Connor6de2e202015-05-21 14:30:41 -070076import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070077import org.onosproject.store.service.EventuallyConsistentMap;
78import org.onosproject.store.service.EventuallyConsistentMapEvent;
79import org.onosproject.store.service.EventuallyConsistentMapListener;
80import org.onosproject.store.service.MultiValuedTimestamp;
81import org.onosproject.store.service.StorageService;
82import org.onosproject.store.service.WallClockTimestamp;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070083import org.slf4j.Logger;
84
Madan Jampani47c93732014-10-06 20:46:08 -070085import java.io.IOException;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070086import java.util.ArrayList;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070087import java.util.Collection;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070088import java.util.Collections;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070089import java.util.HashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070090import java.util.HashSet;
91import java.util.Iterator;
92import java.util.List;
93import java.util.Map;
94import java.util.Map.Entry;
95import java.util.Objects;
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -070096import java.util.Optional;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070097import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070098import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080099import java.util.concurrent.ExecutorService;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700100import java.util.concurrent.ScheduledExecutorService;
101import java.util.concurrent.TimeUnit;
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700102import java.util.stream.Stream;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700103
104import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700105import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700106import static com.google.common.base.Verify.verify;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800107import static java.util.concurrent.Executors.newCachedThreadPool;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800108import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
109import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800110import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800111import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800112import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
113import static org.onosproject.net.DefaultAnnotations.merge;
114import static org.onosproject.net.device.DeviceEvent.Type.*;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800115import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700116import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800117import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700118
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700119/**
120 * Manages inventory of infrastructure devices using gossip protocol to distribute
121 * information.
122 */
123@Component(immediate = true)
124@Service
125public class GossipDeviceStore
126 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
127 implements DeviceStore {
128
129 private final Logger log = getLogger(getClass());
130
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700131 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800132 // Timeout in milliseconds to process device or ports on remote master node
133 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700134
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700135 // innerMap is used to lock a Device, thus instance should never be replaced.
136 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700137 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700138 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700139
140 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700141 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
142 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700143
144 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200145 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700146 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
147 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700148
149 // to be updated under Device lock
150 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
151 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700152
153 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700154 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700155
156 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700157 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700158
Madan Jampani47c93732014-10-06 20:46:08 -0700159 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700160 protected StorageService storageService;
161
162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700163 protected ClusterCommunicationService clusterCommunicator;
164
Madan Jampani53e44e62014-10-07 12:39:51 -0700165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
166 protected ClusterService clusterService;
167
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700168 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
169 protected MastershipService mastershipService;
170
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800171 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
172 protected MastershipTermService termService;
173
174
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700175 protected static final StoreSerializer SERIALIZER = StoreSerializer.using(KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800176 .register(DistributedStoreSerializers.STORE_COMMON)
177 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
178 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
179 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700180 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800181 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
182 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700183 .register(DeviceAntiEntropyAdvertisement.class)
184 .register(DeviceFragmentId.class)
185 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800186 .register(DeviceInjectedEvent.class)
187 .register(PortInjectedEvent.class)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700188 .build("GossipDevice"));
Madan Jampani53e44e62014-10-07 12:39:51 -0700189
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800190 private ExecutorService executor;
191
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800192 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700193
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800194 // TODO make these anti-entropy parameters configurable
195 private long initialDelaySec = 5;
196 private long periodSec = 5;
197
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700198 @Activate
199 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800200 executor = newCachedThreadPool(groupedThreads("onos/device", "fg-%d", log));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800201
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800202 backgroundExecutor =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800203 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d", log)));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700204
Madan Jampani2af244a2015-02-22 13:12:01 -0800205 clusterCommunicator.addSubscriber(
206 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
207 clusterCommunicator.addSubscriber(
208 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
209 new InternalDeviceOfflineEventListener(),
210 executor);
211 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700212 new InternalRemoveRequestListener(),
213 executor);
Madan Jampani2af244a2015-02-22 13:12:01 -0800214 clusterCommunicator.addSubscriber(
215 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
216 clusterCommunicator.addSubscriber(
217 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
218 clusterCommunicator.addSubscriber(
219 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
220 clusterCommunicator.addSubscriber(
221 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
222 new InternalDeviceAdvertisementListener(),
223 backgroundExecutor);
224 clusterCommunicator.addSubscriber(
225 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
226 clusterCommunicator.addSubscriber(
227 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
228
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700229 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800230 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700231 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700232
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700233 // Create a distributed map for port stats.
234 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
235 .register(KryoNamespaces.API)
HIGUCHI Yuta03666a32016-05-18 11:49:09 -0700236 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
237 .register(MultiValuedTimestamp.class);
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700238
239 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
240 .withName("port-stats")
241 .withSerializer(deviceDataSerializer)
242 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700243 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700244 .withTombstonesDisabled()
245 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200246 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
247 eventuallyConsistentMapBuilder()
248 .withName("port-stats-delta")
249 .withSerializer(deviceDataSerializer)
250 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
251 .withTimestampProvider((k, v) -> new WallClockTimestamp())
252 .withTombstonesDisabled()
253 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700254 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700255 log.info("Started");
256 }
257
258 @Deactivate
259 public void deactivate() {
Frank Wange0eb5ce2016-07-01 18:21:25 +0800260 devicePortStats.removeListener(portStatsListener);
Madan Jampani632f16b2015-08-11 12:42:59 -0700261 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200262 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800263 executor.shutdownNow();
264
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800265 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700266 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800267 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700268 log.error("Timeout during executor shutdown");
269 }
270 } catch (InterruptedException e) {
271 log.error("Error during executor shutdown", e);
272 }
273
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700274 deviceDescs.clear();
275 devices.clear();
276 devicePorts.clear();
277 availableDevices.clear();
Frank Wange0eb5ce2016-07-01 18:21:25 +0800278 clusterCommunicator.removeSubscriber(
279 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE);
280 clusterCommunicator.removeSubscriber(
281 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE);
282 clusterCommunicator.removeSubscriber(
283 GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ);
284 clusterCommunicator.removeSubscriber(
285 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED);
286 clusterCommunicator.removeSubscriber(
287 GossipDeviceStoreMessageSubjects.PORT_UPDATE);
288 clusterCommunicator.removeSubscriber(
289 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE);
290 clusterCommunicator.removeSubscriber(
291 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE);
292 clusterCommunicator.removeSubscriber(
293 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED);
294 clusterCommunicator.removeSubscriber(
295 GossipDeviceStoreMessageSubjects.PORT_INJECTED);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700296 log.info("Stopped");
297 }
298
299 @Override
300 public int getDeviceCount() {
301 return devices.size();
302 }
303
304 @Override
305 public Iterable<Device> getDevices() {
306 return Collections.unmodifiableCollection(devices.values());
307 }
308
309 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800310 public Iterable<Device> getAvailableDevices() {
311 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700312 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800313 }
314
315 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700316 public Device getDevice(DeviceId deviceId) {
317 return devices.get(deviceId);
318 }
319
320 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700321 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700322 DeviceId deviceId,
323 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800324 NodeId localNode = clusterService.getLocalNode().id();
325 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
326
327 // Process device update only if we're the master,
328 // otherwise signal the actual master.
329 DeviceEvent deviceEvent = null;
330 if (localNode.equals(deviceNode)) {
331
332 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
333 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
334 final Timestamped<DeviceDescription> mergedDesc;
335 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
336
337 synchronized (device) {
338 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
339 mergedDesc = device.get(providerId).getDeviceDesc();
340 }
341
342 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700343 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
helenyrwufd296b62016-06-22 17:43:02 -0700344 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800345 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
346 }
347
348 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800349 // Only forward for ConfigProvider
350 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800351 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800352 return null;
353 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800354 // FIXME Temporary hack for NPE (ONOS-1171).
355 // Proper fix is to implement forwarding to master on ConfigProvider
356 // redo ONOS-490
357 if (deviceNode == null) {
358 // silently ignore
359 return null;
360 }
361
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800362
363 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
364 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800365
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800366 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700367 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800368 /* error log:
369 log.warn("Failed to process injected device id: {} desc: {} " +
370 "(cluster messaging failed: {})",
371 deviceId, deviceDescription, e);
372 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700373 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800374
375 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700376 }
377
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700378 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700379 DeviceId deviceId,
380 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700381
382 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800383 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700384 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700385
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800386 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700387 // locking per device
388
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700389 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
390 log.debug("Ignoring outdated event: {}", deltaDesc);
391 return null;
392 }
393
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800394 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700395
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700396 final Device oldDevice = devices.get(deviceId);
397 final Device newDevice;
398
399 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700400 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700401 // on new device or valid update
402 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800403 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700404 } else {
405 // outdated event, ignored.
406 return null;
407 }
408 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700409 // REGISTER
410 if (!deltaDesc.value().isDefaultAvailable()) {
411 return registerDevice(providerId, newDevice);
412 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700413 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700414 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700415 } else {
416 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700417 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
418 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700419 }
420 }
421 }
422
423 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700424 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700425 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700426 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700427
428 // update composed device cache
429 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
430 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700431 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
432 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700433
434 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700435 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700436 }
437
438 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
439 }
440
441 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700442 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700443 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700444 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700445 Device newDevice, Timestamp newTimestamp,
446 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700447 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700448 boolean propertiesChanged =
449 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700450 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
451 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700452 boolean annotationsChanged =
453 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700454
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700455 // Primary providers can respond to all changes, but ancillary ones
456 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800457 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700458 if ((providerId.isAncillary() && annotationsChanged) ||
459 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700460 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
461 if (!replaced) {
462 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700463 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800464 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700465 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700466
alshabibdc5d8bd2015-11-02 15:41:29 -0800467 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700468 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800469
helenyrwufd296b62016-06-22 17:43:02 -0700470 if (!providerId.isAncillary() && forceAvailable) {
alshabibdc5d8bd2015-11-02 15:41:29 -0800471 boolean wasOnline = availableDevices.contains(newDevice.id());
472 markOnline(newDevice.id(), newTimestamp);
473 if (!wasOnline) {
474 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
475 }
476 }
477 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700478 }
479
helenyrwufd296b62016-06-22 17:43:02 -0700480 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice) {
481 // update composed device cache
482 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
483 verify(oldDevice == null,
484 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
485 providerId, oldDevice, newDevice);
486
487 if (!providerId.isAncillary()) {
488 markOffline(newDevice.id());
489 }
490
491 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
492 }
493
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700494 @Override
495 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700496 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700497 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700498 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700499 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700500 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800501 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700502 }
503 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700504 }
505
506 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
507
508 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700509 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700510
511 // locking device
512 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700513
514 // accept off-line if given timestamp is newer than
515 // the latest Timestamp from Primary provider
516 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
517 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
518 if (timestamp.compareTo(lastTimestamp) <= 0) {
519 // outdated event ignore
520 return null;
521 }
522
523 offline.put(deviceId, timestamp);
524
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700525 Device device = devices.get(deviceId);
526 if (device == null) {
527 return null;
528 }
529 boolean removed = availableDevices.remove(deviceId);
530 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700531 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700532 }
533 return null;
534 }
535 }
536
helenyrwufd296b62016-06-22 17:43:02 -0700537 public boolean markOnline(DeviceId deviceId) {
538 if (devices.containsKey(deviceId)) {
539 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
540 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
541 synchronized (deviceLock) {
542 if (markOnline(deviceId, timestamp)) {
543 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
544 return true;
545 } else {
546 return false;
547 }
548 }
549 }
550 log.warn("Device {} does not exist in store", deviceId);
551 return false;
552
553 }
554
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700555 /**
556 * Marks the device as available if the given timestamp is not outdated,
557 * compared to the time the device has been marked offline.
558 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700559 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700560 * @param timestamp of the event triggering this change.
561 * @return true if availability change request was accepted and changed the state
562 */
563 // Guarded by deviceDescs value (=Device lock)
564 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
565 // accept on-line if given timestamp is newer than
566 // the latest offline request Timestamp
567 Timestamp offlineTimestamp = offline.get(deviceId);
568 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700569 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700570
571 offline.remove(deviceId);
572 return availableDevices.add(deviceId);
573 }
574 return false;
575 }
576
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700577 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700578 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700579 DeviceId deviceId,
580 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700581
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800582 NodeId localNode = clusterService.getLocalNode().id();
583 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
584 // since it will trigger distributed store read.
585 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
586 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
587 // If we don't care much about topology performance, then it might be OK.
588 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700589
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800590 // Process port update only if we're the master of the device,
591 // otherwise signal the actual master.
592 List<DeviceEvent> deviceEvents = null;
593 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700594
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800595 final Timestamp newTimestamp;
596 try {
597 newTimestamp = deviceClockService.getTimestamp(deviceId);
598 } catch (IllegalStateException e) {
599 log.info("Timestamp was not available for device {}", deviceId);
600 log.debug(" discarding {}", portDescriptions);
601 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700602
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800603 // Possible situation:
604 // Device connected and became master for short period of time,
605 // but lost mastership before this instance had the chance to
606 // retrieve term information.
607
608 // Information dropped here is expected to be recoverable by
609 // device probing after mastership change
610
611 return Collections.emptyList();
612 }
613 log.debug("timestamp for {} {}", deviceId, newTimestamp);
614
615 final Timestamped<List<PortDescription>> timestampedInput
616 = new Timestamped<>(portDescriptions, newTimestamp);
617 final Timestamped<List<PortDescription>> merged;
618
619 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
620
621 synchronized (device) {
622 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
623 final DeviceDescriptions descs = device.get(providerId);
624 List<PortDescription> mergedList =
625 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700626 .transform(input ->
627 // lookup merged port description
628 descs.getPortDesc(input.portNumber()).value()
629 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700630 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800631 }
632
633 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700634 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700635 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800636 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
637 }
638
639 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800640 // Only forward for ConfigProvider
641 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800642 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta89461772016-01-26 12:18:10 -0800643 return Collections.emptyList();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800644 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800645 // FIXME Temporary hack for NPE (ONOS-1171).
646 // Proper fix is to implement forwarding to master on ConfigProvider
647 // redo ONOS-490
648 if (deviceNode == null) {
649 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800650 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800651 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800652
653 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800654
655 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700656 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800657 /* error log:
658 log.warn("Failed to process injected ports of device id: {} " +
659 "(cluster messaging failed: {})",
660 deviceId, e);
661 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700662 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700663
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800664 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700665 }
666
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700667 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700668 DeviceId deviceId,
669 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700670
671 Device device = devices.get(deviceId);
672 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
673
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700674 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700675 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
676
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700677 List<DeviceEvent> events = new ArrayList<>();
678 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700679
680 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
681 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700682 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700683 }
684
685 DeviceDescriptions descs = descsMap.get(providerId);
686 // every provider must provide DeviceDescription.
687 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700688 "Device description for Device ID %s from Provider %s was not found",
689 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700690
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700691 Map<PortNumber, Port> ports = getPortMap(deviceId);
692
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700693 final Timestamp newTimestamp = portDescriptions.timestamp();
694
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700695 // Add new ports
696 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700697 for (PortDescription portDescription : portDescriptions.value()) {
698 final PortNumber number = portDescription.portNumber();
699 processed.add(number);
700
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700701 final Port oldPort = ports.get(number);
702 final Port newPort;
703
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700704
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700705 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
706 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700707 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700708 // on new port or valid update
709 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700710 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700711 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700712 newPort = composePort(device, number, descsMap);
713 } else {
714 // outdated event, ignored.
715 continue;
716 }
717
718 events.add(oldPort == null ?
719 createPort(device, newPort, ports) :
720 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700721 }
722
723 events.addAll(pruneOldPorts(device, ports, processed));
724 }
725 return FluentIterable.from(events).filter(notNull()).toList();
726 }
727
728 // Creates a new port based on the port description adds it to the map and
729 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700730 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700731 private DeviceEvent createPort(Device device, Port newPort,
732 Map<PortNumber, Port> ports) {
733 ports.put(newPort.number(), newPort);
734 return new DeviceEvent(PORT_ADDED, device, newPort);
735 }
736
737 // Checks if the specified port requires update and if so, it replaces the
738 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700739 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700740 private DeviceEvent updatePort(Device device, Port oldPort,
741 Port newPort,
742 Map<PortNumber, Port> ports) {
743 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700744 oldPort.type() != newPort.type() ||
745 oldPort.portSpeed() != newPort.portSpeed() ||
746 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700747 ports.put(oldPort.number(), newPort);
748 return new DeviceEvent(PORT_UPDATED, device, newPort);
749 }
750 return null;
751 }
752
753 // Prunes the specified list of ports based on which ports are in the
754 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700755 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700756 private List<DeviceEvent> pruneOldPorts(Device device,
757 Map<PortNumber, Port> ports,
758 Set<PortNumber> processed) {
759 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700760 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700761 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700762 Entry<PortNumber, Port> e = iterator.next();
763 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700764 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700765 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700766 iterator.remove();
767 }
768 }
769 return events;
770 }
771
772 // Gets the map of ports for the specified device; if one does not already
773 // exist, it creates and registers a new one.
774 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
775 return createIfAbsentUnchecked(devicePorts, deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700776 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700777 }
778
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700779 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700780 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700781 Map<ProviderId, DeviceDescriptions> r;
782 r = deviceDescs.get(deviceId);
783 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700784 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700785 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
786 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
787 if (concurrentlyAdded != null) {
788 r = concurrentlyAdded;
789 }
790 }
791 return r;
792 }
793
794 // Guarded by deviceDescs value (=Device lock)
795 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
796 Map<ProviderId, DeviceDescriptions> device,
797 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700798 synchronized (device) {
799 DeviceDescriptions r = device.get(providerId);
800 if (r == null) {
801 r = new DeviceDescriptions(deltaDesc);
802 device.put(providerId, r);
803 }
804 return r;
805 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700806 }
807
808 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700809 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
810 DeviceId deviceId,
811 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700812 final Timestamp newTimestamp;
813 try {
814 newTimestamp = deviceClockService.getTimestamp(deviceId);
815 } catch (IllegalStateException e) {
816 log.info("Timestamp was not available for device {}", deviceId);
817 log.debug(" discarding {}", portDescription);
818 // Failed to generate timestamp. Ignoring.
819 // See updatePorts comment
820 return null;
821 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700822 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700823 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700824 final DeviceEvent event;
825 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800826 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
827 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700828 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800829 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700830 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700831 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700832 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700833 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700834 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800835 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700836 }
837 return event;
838 }
839
840 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700841 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700842 Device device = devices.get(deviceId);
843 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
844
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700845 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700846 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
847
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700848 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700849
850 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
851 log.debug("Ignoring outdated event: {}", deltaDesc);
852 return null;
853 }
854
855 DeviceDescriptions descs = descsMap.get(providerId);
856 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700857 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700858 "Device description for Device ID %s from Provider %s was not found",
859 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700860
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700861 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
862 final PortNumber number = deltaDesc.value().portNumber();
863 final Port oldPort = ports.get(number);
864 final Port newPort;
865
866 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
867 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700868 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700869 // on new port or valid update
870 // update description
871 descs.putPortDesc(deltaDesc);
872 newPort = composePort(device, number, descsMap);
873 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700874 // same or outdated event, ignored.
875 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700876 return null;
877 }
878
879 if (oldPort == null) {
880 return createPort(device, newPort, ports);
881 } else {
882 return updatePort(device, oldPort, newPort, ports);
883 }
884 }
885 }
886
887 @Override
888 public List<Port> getPorts(DeviceId deviceId) {
889 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
890 if (ports == null) {
891 return Collections.emptyList();
892 }
893 return ImmutableList.copyOf(ports.values());
894 }
895
896 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700897 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
898 DeviceId deviceId) {
899 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
900 if (descs == null) {
901 return null;
902 }
903 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
904 final Optional<DeviceDescriptions> devDescs;
905 synchronized (descs) {
906 devDescs = Optional.ofNullable(descs.get(pid));
907 }
908 // DeviceDescriptions is concurrent access-safe
909 return devDescs
910 .map(dd -> dd.getPortDescs().values().stream()
911 .map(Timestamped::value))
912 .orElse(Stream.empty());
913 }
914
915 @Override
sangho538108b2015-04-08 14:29:20 -0700916 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200917 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700918
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200919 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
920 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
921 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
922
923 if (prvStatsMap != null) {
924 for (PortStatistics newStats : newStatsCollection) {
925 PortNumber port = PortNumber.portNumber(newStats.port());
926 PortStatistics prvStats = prvStatsMap.get(port);
927 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
928 PortStatistics deltaStats = builder.build();
929 if (prvStats != null) {
930 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
931 }
932 deltaStatsMap.put(port, deltaStats);
933 newStatsMap.put(port, newStats);
934 }
935 } else {
936 for (PortStatistics newStats : newStatsCollection) {
937 PortNumber port = PortNumber.portNumber(newStats.port());
938 newStatsMap.put(port, newStats);
939 }
sangho538108b2015-04-08 14:29:20 -0700940 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200941 devicePortDeltaStats.put(deviceId, deltaStatsMap);
942 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200943 // DeviceEvent returns null because of InternalPortStatsListener usage
944 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200945 }
946
947 /**
948 * Calculate delta statistics by subtracting previous from new statistics.
949 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700950 * @param deviceId device identifier
951 * @param prvStats previous port statistics
952 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200953 * @return PortStatistics
954 */
955 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
956 // calculate time difference
957 long deltaStatsSec, deltaStatsNano;
958 if (newStats.durationNano() < prvStats.durationNano()) {
959 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
960 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
961 } else {
962 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
963 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
964 }
965 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
966 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
967 .setPort(newStats.port())
968 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
969 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
970 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
971 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
972 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
973 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
974 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
975 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
976 .setDurationSec(deltaStatsSec)
977 .setDurationNano(deltaStatsNano)
978 .build();
979 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700980 }
981
982 @Override
983 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700984 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
985 if (portStats == null) {
986 return Collections.emptyList();
987 }
988 return ImmutableList.copyOf(portStats.values());
989 }
990
991 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200992 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
993 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
994 if (portStats == null) {
995 return Collections.emptyList();
996 }
997 return ImmutableList.copyOf(portStats.values());
998 }
999
1000 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001001 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
1002 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1003 return ports == null ? null : ports.get(portNumber);
1004 }
1005
1006 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -07001007 public PortDescription getPortDescription(ProviderId pid,
1008 DeviceId deviceId,
1009 PortNumber portNumber) {
1010 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1011 if (descs == null) {
1012 return null;
1013 }
1014 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1015 final Optional<DeviceDescriptions> devDescs;
1016 synchronized (descs) {
1017 devDescs = Optional.ofNullable(descs.get(pid));
1018 }
1019 // DeviceDescriptions is concurrent access-safe
1020 return devDescs
1021 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1022 .map(Timestamped::value)
1023 .orElse(null);
1024 }
1025
1026 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001027 public boolean isAvailable(DeviceId deviceId) {
1028 return availableDevices.contains(deviceId);
1029 }
1030
1031 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001032 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001033 final NodeId myId = clusterService.getLocalNode().id();
1034 NodeId master = mastershipService.getMasterFor(deviceId);
1035
1036 // if there exist a master, forward
1037 // if there is no master, try to become one and process
1038
1039 boolean relinquishAtEnd = false;
1040 if (master == null) {
1041 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1042 if (myRole != MastershipRole.NONE) {
1043 relinquishAtEnd = true;
1044 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001045 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001046 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001047 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -07001048 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001049 master = myId;
1050 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001051 }
1052
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001053 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001054 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001055 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001056
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001057 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001058 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001059 /* error log:
1060 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1061 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001062
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001063 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001064 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001065 }
1066
1067 // I have control..
1068
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -07001069 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001070 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001071 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001072 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001073 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001074 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001075 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001076 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001077 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001078 mastershipService.relinquishMastership(deviceId);
1079 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001080 return event;
1081 }
1082
1083 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
1084 Timestamp timestamp) {
1085
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001086 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001087 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001088 // accept removal request if given timestamp is newer than
1089 // the latest Timestamp from Primary provider
1090 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001091 if (primDescs == null) {
1092 return null;
1093 }
1094
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001095 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
1096 if (timestamp.compareTo(lastTimestamp) <= 0) {
1097 // outdated event ignore
1098 return null;
1099 }
1100 removalRequest.put(deviceId, timestamp);
1101
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001102 Device device = devices.remove(deviceId);
1103 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001104 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1105 if (ports != null) {
1106 ports.clear();
1107 }
1108 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001109 descs.clear();
1110 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001111 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001112 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001113 }
1114
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001115 /**
1116 * Checks if given timestamp is superseded by removal request
1117 * with more recent timestamp.
1118 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001119 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001120 * @param timestampToCheck timestamp of an event to check
1121 * @return true if device is already removed
1122 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001123 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1124 Timestamp removalTimestamp = removalRequest.get(deviceId);
1125 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001126 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001127 // removalRequest is more recent
1128 return true;
1129 }
1130 return false;
1131 }
1132
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001133 /**
1134 * Returns a Device, merging description given from multiple Providers.
1135 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001136 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001137 * @param providerDescs Collection of Descriptions from multiple providers
1138 * @return Device instance
1139 */
1140 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001141 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001142
Thomas Vachuska444eda62014-10-28 13:09:42 -07001143 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001144
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001145 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001146
1147 DeviceDescriptions desc = providerDescs.get(primary);
1148
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001149 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001150 Type type = base.type();
1151 String manufacturer = base.manufacturer();
1152 String hwVersion = base.hwVersion();
1153 String swVersion = base.swVersion();
1154 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001155 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001156 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1157 annotations = merge(annotations, base.annotations());
1158
1159 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1160 if (e.getKey().equals(primary)) {
1161 continue;
1162 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001163 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001164 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001165 // Currently assuming there will never be a key conflict between
1166 // providers
1167
1168 // annotation merging. not so efficient, should revisit later
1169 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1170 }
1171
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001172 return new DefaultDevice(primary, deviceId, type, manufacturer,
1173 hwVersion, swVersion, serialNumber,
1174 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001175 }
1176
Marc De Leenheer88194c32015-05-29 22:10:59 -07001177 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1178 PortDescription description, Annotations annotations) {
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001179 // FIXME this switch need to go away once all ports are done.
Marc De Leenheer88194c32015-05-29 22:10:59 -07001180 switch (description.type()) {
1181 case OMS:
HIGUCHI Yuta95d83e82016-04-26 12:13:48 -07001182 if (description instanceof OmsPortDescription) {
1183 // remove if-block once deprecation is complete
1184 OmsPortDescription omsDesc = (OmsPortDescription) description;
1185 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1186 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1187 }
1188 // same as default
1189 return new DefaultPort(device, number, isEnabled, description.type(),
1190 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001191 case OCH:
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001192 if (description instanceof OchPortDescription) {
1193 // remove if-block once Och deprecation is complete
1194 OchPortDescription ochDesc = (OchPortDescription) description;
1195 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1196 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1197 }
1198 return new DefaultPort(device, number, isEnabled, description.type(),
1199 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001200 case ODUCLT:
HIGUCHI Yuta4c0ef6b2016-05-02 19:45:41 -07001201 if (description instanceof OduCltPortDescription) {
1202 // remove if-block once deprecation is complete
1203 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1204 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1205 }
1206 // same as default
1207 return new DefaultPort(device, number, isEnabled, description.type(),
1208 description.portSpeed(), annotations);
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +02001209 case OTU:
HIGUCHI Yuta5be3e822016-05-03 13:51:42 -07001210 if (description instanceof OtuPortDescription) {
1211 // remove if-block once deprecation is complete
1212 OtuPortDescription otuDesc = (OtuPortDescription) description;
1213 return new OtuPort(device, number, isEnabled, otuDesc.signalType(), annotations);
1214 }
1215 // same as default
1216 return new DefaultPort(device, number, isEnabled, description.type(),
1217 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001218 default:
1219 return new DefaultPort(device, number, isEnabled, description.type(),
1220 description.portSpeed(), annotations);
1221 }
1222 }
1223
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001224 /**
1225 * Returns a Port, merging description given from multiple Providers.
1226 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001227 * @param device device the port is on
1228 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001229 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001230 * @return Port instance
1231 */
1232 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001233 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001234
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001235 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001236 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001237 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001238 boolean isEnabled = false;
1239 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001240 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001241 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1242 if (portDesc != null) {
1243 isEnabled = portDesc.value().isEnabled();
1244 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001245 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001246 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001247 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001248 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001249 if (e.getKey().equals(primary)) {
1250 continue;
1251 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001252 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001253 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001254 // Currently assuming there will never be a key conflict between
1255 // providers
1256
1257 // annotation merging. not so efficient, should revisit later
1258 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1259 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001260 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1261 continue;
1262 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001263 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001264 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001265 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001266 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001267 }
1268 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001269 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001270 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001271 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001272 PortDescription current = portDesc.value();
1273 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001274 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001275 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001276 }
1277
1278 /**
1279 * @return primary ProviderID, or randomly chosen one if none exists
1280 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001281 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001282 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001283 ProviderId fallBackPrimary = null;
1284 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1285 if (!e.getKey().isAncillary()) {
1286 return e.getKey();
1287 } else if (fallBackPrimary == null) {
1288 // pick randomly as a fallback in case there is no primary
1289 fallBackPrimary = e.getKey();
1290 }
1291 }
1292 return fallBackPrimary;
1293 }
1294
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001295 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001296 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001297 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001298 return providerDescs.get(pid);
1299 }
1300
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001301 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001302 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001303 }
1304
Jonathan Hart7d656f42015-01-27 14:07:23 -08001305 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001306 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001307 }
Madan Jampani47c93732014-10-06 20:46:08 -07001308
Jonathan Hart7d656f42015-01-27 14:07:23 -08001309 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001310 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001311 }
1312
Jonathan Hart7d656f42015-01-27 14:07:23 -08001313 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001314 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001315 }
1316
Jonathan Hart7d656f42015-01-27 14:07:23 -08001317 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001318 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001319 }
1320
Jonathan Hart7d656f42015-01-27 14:07:23 -08001321 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001322 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001323 }
1324
Jonathan Hart7d656f42015-01-27 14:07:23 -08001325 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001326 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1327 }
1328
1329 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1330 try {
1331 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1332 } catch (IOException e) {
1333 log.error("Failed to send" + event + " to " + recipient, e);
1334 }
1335 }
1336
1337 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1338 try {
1339 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1340 } catch (IOException e) {
1341 log.error("Failed to send" + event + " to " + recipient, e);
1342 }
1343 }
1344
1345 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1346 try {
1347 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1348 } catch (IOException e) {
1349 log.error("Failed to send" + event + " to " + recipient, e);
1350 }
1351 }
1352
1353 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1354 try {
1355 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1356 } catch (IOException e) {
1357 log.error("Failed to send" + event + " to " + recipient, e);
1358 }
1359 }
1360
1361 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1362 try {
1363 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1364 } catch (IOException e) {
1365 log.error("Failed to send" + event + " to " + recipient, e);
1366 }
1367 }
1368
1369 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1370 final NodeId self = clusterService.getLocalNode().id();
1371
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001372 final int numDevices = deviceDescs.size();
1373 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1374 final int portsPerDevice = 8; // random factor to minimize reallocation
1375 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1376 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001377
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001378 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001379
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001380 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001381 synchronized (devDescs) {
1382
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001383 // send device offline timestamp
1384 Timestamp lOffline = this.offline.get(deviceId);
1385 if (lOffline != null) {
1386 adOffline.put(deviceId, lOffline);
1387 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001388
1389 for (Entry<ProviderId, DeviceDescriptions>
1390 prov : devDescs.entrySet()) {
1391
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001392 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001393 final ProviderId provId = prov.getKey();
1394 final DeviceDescriptions descs = prov.getValue();
1395
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001396 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001397 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001398
1399 for (Entry<PortNumber, Timestamped<PortDescription>>
1400 portDesc : descs.getPortDescs().entrySet()) {
1401
1402 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001403 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001404 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001405 }
1406 }
1407 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001408 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001409
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001410 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001411 }
1412
1413 /**
1414 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001415 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001416 * Notify sender about out-dated information using regular replication message.
1417 * Send back advertisement to sender if not in sync.
1418 *
1419 * @param advertisement to respond to
1420 */
1421 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1422
1423 final NodeId sender = advertisement.sender();
1424
1425 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1426 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1427 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1428
1429 // Fragments to request
1430 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1431 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1432
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001433 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001434 final DeviceId deviceId = de.getKey();
1435 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1436
1437 synchronized (lDevice) {
1438 // latestTimestamp across provider
1439 // Note: can be null initially
1440 Timestamp localLatest = offline.get(deviceId);
1441
1442 // handle device Ads
1443 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1444 final ProviderId provId = prov.getKey();
1445 final DeviceDescriptions lDeviceDescs = prov.getValue();
1446
1447 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1448
1449
1450 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1451 Timestamp advDevTimestamp = devAds.get(devFragId);
1452
Jonathan Hart403ea932015-02-20 16:23:00 -08001453 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1454 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001455 // remote does not have it or outdated, suggest
1456 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1457 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1458 // local is outdated, request
1459 reqDevices.add(devFragId);
1460 }
1461
1462 // handle port Ads
1463 for (Entry<PortNumber, Timestamped<PortDescription>>
1464 pe : lDeviceDescs.getPortDescs().entrySet()) {
1465
1466 final PortNumber num = pe.getKey();
1467 final Timestamped<PortDescription> lPort = pe.getValue();
1468
1469 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1470
1471 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001472 if (advPortTimestamp == null || lPort.isNewerThan(
1473 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001474 // remote does not have it or outdated, suggest
1475 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1476 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1477 // local is outdated, request
1478 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1479 reqPorts.add(portFragId);
1480 }
1481
1482 // remove port Ad already processed
1483 portAds.remove(portFragId);
1484 } // end local port loop
1485
1486 // remove device Ad already processed
1487 devAds.remove(devFragId);
1488
1489 // find latest and update
1490 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1491 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001492 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001493 localLatest = providerLatest;
1494 }
1495 } // end local provider loop
1496
1497 // checking if remote timestamp is more recent.
1498 Timestamp rOffline = offlineAds.get(deviceId);
1499 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001500 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001501 // remote offline timestamp suggests that the
1502 // device is off-line
1503 markOfflineInternal(deviceId, rOffline);
1504 }
1505
1506 Timestamp lOffline = offline.get(deviceId);
1507 if (lOffline != null && rOffline == null) {
1508 // locally offline, but remote is online, suggest offline
1509 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1510 }
1511
1512 // remove device offline Ad already processed
1513 offlineAds.remove(deviceId);
1514 } // end local device loop
1515 } // device lock
1516
1517 // If there is any Ads left, request them
1518 log.trace("Ads left {}, {}", devAds, portAds);
1519 reqDevices.addAll(devAds.keySet());
1520 reqPorts.addAll(portAds.keySet());
1521
1522 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1523 log.trace("Nothing to request to remote peer {}", sender);
1524 return;
1525 }
1526
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001527 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001528
1529 // 2-way Anti-Entropy for now
1530 try {
1531 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1532 } catch (IOException e) {
1533 log.error("Failed to send response advertisement to " + sender, e);
1534 }
1535
1536// Sketch of 3-way Anti-Entropy
1537// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1538// ClusterMessage message = new ClusterMessage(
1539// clusterService.getLocalNode().id(),
1540// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1541// SERIALIZER.encode(request));
1542//
1543// try {
1544// clusterCommunicator.unicast(message, advertisement.sender());
1545// } catch (IOException e) {
1546// log.error("Failed to send advertisement reply to "
1547// + advertisement.sender(), e);
1548// }
Madan Jampani47c93732014-10-06 20:46:08 -07001549 }
1550
Madan Jampani255a58b2014-10-09 12:08:20 -07001551 private void notifyDelegateIfNotNull(DeviceEvent event) {
1552 if (event != null) {
1553 notifyDelegate(event);
1554 }
1555 }
1556
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001557 private final class SendAdvertisementTask implements Runnable {
1558
1559 @Override
1560 public void run() {
1561 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001562 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001563 return;
1564 }
1565
1566 try {
1567 final NodeId self = clusterService.getLocalNode().id();
1568 Set<ControllerNode> nodes = clusterService.getNodes();
1569
1570 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1571 .transform(toNodeId())
1572 .toList();
1573
1574 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001575 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001576 return;
1577 }
1578
1579 NodeId peer;
1580 do {
1581 int idx = RandomUtils.nextInt(0, nodeIds.size());
1582 peer = nodeIds.get(idx);
1583 } while (peer.equals(self));
1584
1585 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1586
1587 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001588 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001589 return;
1590 }
1591
1592 try {
1593 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1594 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001595 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001596 return;
1597 }
1598 } catch (Exception e) {
1599 // catch all Exception to avoid Scheduled task being suppressed.
1600 log.error("Exception thrown while sending advertisement", e);
1601 }
1602 }
1603 }
1604
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001605 private final class InternalDeviceEventListener
1606 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001607 @Override
1608 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001609 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001610 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001611
Madan Jampani47c93732014-10-06 20:46:08 -07001612 ProviderId providerId = event.providerId();
1613 DeviceId deviceId = event.deviceId();
1614 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001615
Madan Jampani2af244a2015-02-22 13:12:01 -08001616 try {
helenyrwufd296b62016-06-22 17:43:02 -07001617 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1618 deviceDescription));
Madan Jampani2af244a2015-02-22 13:12:01 -08001619 } catch (Exception e) {
1620 log.warn("Exception thrown handling device update", e);
1621 }
Madan Jampani47c93732014-10-06 20:46:08 -07001622 }
1623 }
1624
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001625 private final class InternalDeviceOfflineEventListener
1626 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001627 @Override
1628 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001629 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001630 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001631
1632 DeviceId deviceId = event.deviceId();
1633 Timestamp timestamp = event.timestamp();
1634
Madan Jampani2af244a2015-02-22 13:12:01 -08001635 try {
1636 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1637 } catch (Exception e) {
1638 log.warn("Exception thrown handling device offline", e);
1639 }
Madan Jampani25322532014-10-08 11:20:38 -07001640 }
1641 }
1642
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001643 private final class InternalRemoveRequestListener
1644 implements ClusterMessageHandler {
1645 @Override
1646 public void handle(ClusterMessage message) {
1647 log.debug("Received device remove request from peer: {}", message.sender());
1648 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001649
Madan Jampani2af244a2015-02-22 13:12:01 -08001650 try {
1651 removeDevice(did);
1652 } catch (Exception e) {
1653 log.warn("Exception thrown handling device remove", e);
1654 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001655 }
1656 }
1657
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001658 private final class InternalDeviceRemovedEventListener
1659 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001660 @Override
1661 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001662 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001663 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001664
1665 DeviceId deviceId = event.deviceId();
1666 Timestamp timestamp = event.timestamp();
1667
Madan Jampani2af244a2015-02-22 13:12:01 -08001668 try {
1669 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1670 } catch (Exception e) {
1671 log.warn("Exception thrown handling device removed", e);
1672 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001673 }
1674 }
1675
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001676 private final class InternalPortEventListener
1677 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001678 @Override
1679 public void handle(ClusterMessage message) {
1680
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001681 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001682 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001683
1684 ProviderId providerId = event.providerId();
1685 DeviceId deviceId = event.deviceId();
1686 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1687
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001688 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001689 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001690 // Note: dropped information will be recovered by anti-entropy
1691 return;
1692 }
1693
Madan Jampani2af244a2015-02-22 13:12:01 -08001694 try {
1695 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1696 } catch (Exception e) {
1697 log.warn("Exception thrown handling port update", e);
1698 }
Madan Jampani47c93732014-10-06 20:46:08 -07001699 }
1700 }
1701
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001702 private final class InternalPortStatusEventListener
1703 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001704 @Override
1705 public void handle(ClusterMessage message) {
1706
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001707 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001708 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001709
1710 ProviderId providerId = event.providerId();
1711 DeviceId deviceId = event.deviceId();
1712 Timestamped<PortDescription> portDescription = event.portDescription();
1713
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001714 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001715 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001716 // Note: dropped information will be recovered by anti-entropy
1717 return;
1718 }
1719
Madan Jampani2af244a2015-02-22 13:12:01 -08001720 try {
1721 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1722 } catch (Exception e) {
1723 log.warn("Exception thrown handling port update", e);
1724 }
Madan Jampani47c93732014-10-06 20:46:08 -07001725 }
1726 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001727
1728 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001729 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001730 @Override
1731 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001732 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001733 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001734 try {
1735 handleAdvertisement(advertisement);
1736 } catch (Exception e) {
1737 log.warn("Exception thrown handling Device advertisements.", e);
1738 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001739 }
1740 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001741
1742 private final class DeviceInjectedEventListener
1743 implements ClusterMessageHandler {
1744 @Override
1745 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001746 log.debug("Received injected device event from peer: {}", message.sender());
1747 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1748
1749 ProviderId providerId = event.providerId();
1750 DeviceId deviceId = event.deviceId();
1751 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001752 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1753 // workaround for ONOS-1208
1754 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1755 return;
1756 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001757
Madan Jampani2af244a2015-02-22 13:12:01 -08001758 try {
1759 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1760 } catch (Exception e) {
1761 log.warn("Exception thrown handling device injected event.", e);
1762 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001763 }
1764 }
1765
1766 private final class PortInjectedEventListener
1767 implements ClusterMessageHandler {
1768 @Override
1769 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001770 log.debug("Received injected port event from peer: {}", message.sender());
1771 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1772
1773 ProviderId providerId = event.providerId();
1774 DeviceId deviceId = event.deviceId();
1775 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001776 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1777 // workaround for ONOS-1208
1778 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1779 return;
1780 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001781
Madan Jampani2af244a2015-02-22 13:12:01 -08001782 try {
1783 updatePorts(providerId, deviceId, portDescriptions);
1784 } catch (Exception e) {
1785 log.warn("Exception thrown handling port injected event.", e);
1786 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001787 }
1788 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001789
1790 private class InternalPortStatsListener
1791 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1792 @Override
1793 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1794 if (event.type() == PUT) {
1795 Device device = devices.get(event.key());
1796 if (device != null) {
1797 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1798 }
1799 }
1800 }
1801 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001802}