blob: 49c8534b7e877a22b69771a5924b6baa86ba5ef9 [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: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -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) {
409 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700410 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700411 } else {
412 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700413 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700414 }
415 }
416 }
417
418 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700419 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700420 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700421 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700422
423 // update composed device cache
424 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
425 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700426 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
427 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700428
429 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700430 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700431 }
432
433 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
434 }
435
436 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700437 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700438 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700439 Device oldDevice,
440 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700441 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700442 boolean propertiesChanged =
443 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700444 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
445 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700446 boolean annotationsChanged =
447 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700448
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700449 // Primary providers can respond to all changes, but ancillary ones
450 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800451 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700452 if ((providerId.isAncillary() && annotationsChanged) ||
453 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700454 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
455 if (!replaced) {
456 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700457 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800458 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700459 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700460
alshabibdc5d8bd2015-11-02 15:41:29 -0800461 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700462 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800463
464 if (!providerId.isAncillary()) {
465 boolean wasOnline = availableDevices.contains(newDevice.id());
466 markOnline(newDevice.id(), newTimestamp);
467 if (!wasOnline) {
468 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
469 }
470 }
471 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700472 }
473
474 @Override
475 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700476 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700477 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700478 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700479 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700480 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800481 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700482 }
483 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700484 }
485
486 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
487
488 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700489 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700490
491 // locking device
492 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700493
494 // accept off-line if given timestamp is newer than
495 // the latest Timestamp from Primary provider
496 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
497 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
498 if (timestamp.compareTo(lastTimestamp) <= 0) {
499 // outdated event ignore
500 return null;
501 }
502
503 offline.put(deviceId, timestamp);
504
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700505 Device device = devices.get(deviceId);
506 if (device == null) {
507 return null;
508 }
509 boolean removed = availableDevices.remove(deviceId);
510 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700511 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700512 }
513 return null;
514 }
515 }
516
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700517 /**
518 * Marks the device as available if the given timestamp is not outdated,
519 * compared to the time the device has been marked offline.
520 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700521 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700522 * @param timestamp of the event triggering this change.
523 * @return true if availability change request was accepted and changed the state
524 */
525 // Guarded by deviceDescs value (=Device lock)
526 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
527 // accept on-line if given timestamp is newer than
528 // the latest offline request Timestamp
529 Timestamp offlineTimestamp = offline.get(deviceId);
530 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700531 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700532
533 offline.remove(deviceId);
534 return availableDevices.add(deviceId);
535 }
536 return false;
537 }
538
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700539 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700540 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700541 DeviceId deviceId,
542 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700543
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800544 NodeId localNode = clusterService.getLocalNode().id();
545 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
546 // since it will trigger distributed store read.
547 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
548 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
549 // If we don't care much about topology performance, then it might be OK.
550 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700551
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800552 // Process port update only if we're the master of the device,
553 // otherwise signal the actual master.
554 List<DeviceEvent> deviceEvents = null;
555 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700556
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800557 final Timestamp newTimestamp;
558 try {
559 newTimestamp = deviceClockService.getTimestamp(deviceId);
560 } catch (IllegalStateException e) {
561 log.info("Timestamp was not available for device {}", deviceId);
562 log.debug(" discarding {}", portDescriptions);
563 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700564
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800565 // Possible situation:
566 // Device connected and became master for short period of time,
567 // but lost mastership before this instance had the chance to
568 // retrieve term information.
569
570 // Information dropped here is expected to be recoverable by
571 // device probing after mastership change
572
573 return Collections.emptyList();
574 }
575 log.debug("timestamp for {} {}", deviceId, newTimestamp);
576
577 final Timestamped<List<PortDescription>> timestampedInput
578 = new Timestamped<>(portDescriptions, newTimestamp);
579 final Timestamped<List<PortDescription>> merged;
580
581 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
582
583 synchronized (device) {
584 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
585 final DeviceDescriptions descs = device.get(providerId);
586 List<PortDescription> mergedList =
587 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700588 .transform(input ->
589 // lookup merged port description
590 descs.getPortDesc(input.portNumber()).value()
591 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700592 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800593 }
594
595 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700596 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700597 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800598 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
599 }
600
601 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800602 // Only forward for ConfigProvider
603 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800604 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta89461772016-01-26 12:18:10 -0800605 return Collections.emptyList();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800606 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800607 // FIXME Temporary hack for NPE (ONOS-1171).
608 // Proper fix is to implement forwarding to master on ConfigProvider
609 // redo ONOS-490
610 if (deviceNode == null) {
611 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800612 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800613 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800614
615 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800616
617 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700618 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800619 /* error log:
620 log.warn("Failed to process injected ports of device id: {} " +
621 "(cluster messaging failed: {})",
622 deviceId, e);
623 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700624 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700625
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800626 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700627 }
628
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700629 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700630 DeviceId deviceId,
631 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700632
633 Device device = devices.get(deviceId);
634 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
635
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700636 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700637 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
638
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700639 List<DeviceEvent> events = new ArrayList<>();
640 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700641
642 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
643 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700644 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700645 }
646
647 DeviceDescriptions descs = descsMap.get(providerId);
648 // every provider must provide DeviceDescription.
649 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700650 "Device description for Device ID %s from Provider %s was not found",
651 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700652
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700653 Map<PortNumber, Port> ports = getPortMap(deviceId);
654
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700655 final Timestamp newTimestamp = portDescriptions.timestamp();
656
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700657 // Add new ports
658 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700659 for (PortDescription portDescription : portDescriptions.value()) {
660 final PortNumber number = portDescription.portNumber();
661 processed.add(number);
662
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700663 final Port oldPort = ports.get(number);
664 final Port newPort;
665
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700666
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700667 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
668 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700669 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700670 // on new port or valid update
671 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700672 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700673 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700674 newPort = composePort(device, number, descsMap);
675 } else {
676 // outdated event, ignored.
677 continue;
678 }
679
680 events.add(oldPort == null ?
681 createPort(device, newPort, ports) :
682 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700683 }
684
685 events.addAll(pruneOldPorts(device, ports, processed));
686 }
687 return FluentIterable.from(events).filter(notNull()).toList();
688 }
689
690 // Creates a new port based on the port description adds it to the map and
691 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700692 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700693 private DeviceEvent createPort(Device device, Port newPort,
694 Map<PortNumber, Port> ports) {
695 ports.put(newPort.number(), newPort);
696 return new DeviceEvent(PORT_ADDED, device, newPort);
697 }
698
699 // Checks if the specified port requires update and if so, it replaces the
700 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700701 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700702 private DeviceEvent updatePort(Device device, Port oldPort,
703 Port newPort,
704 Map<PortNumber, Port> ports) {
705 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700706 oldPort.type() != newPort.type() ||
707 oldPort.portSpeed() != newPort.portSpeed() ||
708 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700709 ports.put(oldPort.number(), newPort);
710 return new DeviceEvent(PORT_UPDATED, device, newPort);
711 }
712 return null;
713 }
714
715 // Prunes the specified list of ports based on which ports are in the
716 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700717 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700718 private List<DeviceEvent> pruneOldPorts(Device device,
719 Map<PortNumber, Port> ports,
720 Set<PortNumber> processed) {
721 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700722 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700723 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700724 Entry<PortNumber, Port> e = iterator.next();
725 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700726 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700727 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700728 iterator.remove();
729 }
730 }
731 return events;
732 }
733
734 // Gets the map of ports for the specified device; if one does not already
735 // exist, it creates and registers a new one.
736 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
737 return createIfAbsentUnchecked(devicePorts, deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700738 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700739 }
740
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700741 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700742 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700743 Map<ProviderId, DeviceDescriptions> r;
744 r = deviceDescs.get(deviceId);
745 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700746 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700747 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
748 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
749 if (concurrentlyAdded != null) {
750 r = concurrentlyAdded;
751 }
752 }
753 return r;
754 }
755
756 // Guarded by deviceDescs value (=Device lock)
757 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
758 Map<ProviderId, DeviceDescriptions> device,
759 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700760 synchronized (device) {
761 DeviceDescriptions r = device.get(providerId);
762 if (r == null) {
763 r = new DeviceDescriptions(deltaDesc);
764 device.put(providerId, r);
765 }
766 return r;
767 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700768 }
769
770 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700771 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
772 DeviceId deviceId,
773 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700774 final Timestamp newTimestamp;
775 try {
776 newTimestamp = deviceClockService.getTimestamp(deviceId);
777 } catch (IllegalStateException e) {
778 log.info("Timestamp was not available for device {}", deviceId);
779 log.debug(" discarding {}", portDescription);
780 // Failed to generate timestamp. Ignoring.
781 // See updatePorts comment
782 return null;
783 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700784 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700785 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700786 final DeviceEvent event;
787 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800788 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
789 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700790 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800791 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700792 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700793 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700794 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700795 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700796 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800797 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700798 }
799 return event;
800 }
801
802 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700803 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700804 Device device = devices.get(deviceId);
805 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
806
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700807 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700808 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
809
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700810 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700811
812 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
813 log.debug("Ignoring outdated event: {}", deltaDesc);
814 return null;
815 }
816
817 DeviceDescriptions descs = descsMap.get(providerId);
818 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700819 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700820 "Device description for Device ID %s from Provider %s was not found",
821 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700822
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700823 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
824 final PortNumber number = deltaDesc.value().portNumber();
825 final Port oldPort = ports.get(number);
826 final Port newPort;
827
828 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
829 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700830 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700831 // on new port or valid update
832 // update description
833 descs.putPortDesc(deltaDesc);
834 newPort = composePort(device, number, descsMap);
835 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700836 // same or outdated event, ignored.
837 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700838 return null;
839 }
840
841 if (oldPort == null) {
842 return createPort(device, newPort, ports);
843 } else {
844 return updatePort(device, oldPort, newPort, ports);
845 }
846 }
847 }
848
849 @Override
850 public List<Port> getPorts(DeviceId deviceId) {
851 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
852 if (ports == null) {
853 return Collections.emptyList();
854 }
855 return ImmutableList.copyOf(ports.values());
856 }
857
858 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700859 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
860 DeviceId deviceId) {
861 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
862 if (descs == null) {
863 return null;
864 }
865 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
866 final Optional<DeviceDescriptions> devDescs;
867 synchronized (descs) {
868 devDescs = Optional.ofNullable(descs.get(pid));
869 }
870 // DeviceDescriptions is concurrent access-safe
871 return devDescs
872 .map(dd -> dd.getPortDescs().values().stream()
873 .map(Timestamped::value))
874 .orElse(Stream.empty());
875 }
876
877 @Override
sangho538108b2015-04-08 14:29:20 -0700878 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200879 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700880
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200881 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
882 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
883 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
884
885 if (prvStatsMap != null) {
886 for (PortStatistics newStats : newStatsCollection) {
887 PortNumber port = PortNumber.portNumber(newStats.port());
888 PortStatistics prvStats = prvStatsMap.get(port);
889 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
890 PortStatistics deltaStats = builder.build();
891 if (prvStats != null) {
892 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
893 }
894 deltaStatsMap.put(port, deltaStats);
895 newStatsMap.put(port, newStats);
896 }
897 } else {
898 for (PortStatistics newStats : newStatsCollection) {
899 PortNumber port = PortNumber.portNumber(newStats.port());
900 newStatsMap.put(port, newStats);
901 }
sangho538108b2015-04-08 14:29:20 -0700902 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200903 devicePortDeltaStats.put(deviceId, deltaStatsMap);
904 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200905 // DeviceEvent returns null because of InternalPortStatsListener usage
906 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200907 }
908
909 /**
910 * Calculate delta statistics by subtracting previous from new statistics.
911 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700912 * @param deviceId device identifier
913 * @param prvStats previous port statistics
914 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200915 * @return PortStatistics
916 */
917 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
918 // calculate time difference
919 long deltaStatsSec, deltaStatsNano;
920 if (newStats.durationNano() < prvStats.durationNano()) {
921 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
922 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
923 } else {
924 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
925 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
926 }
927 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
928 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
929 .setPort(newStats.port())
930 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
931 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
932 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
933 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
934 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
935 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
936 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
937 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
938 .setDurationSec(deltaStatsSec)
939 .setDurationNano(deltaStatsNano)
940 .build();
941 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700942 }
943
944 @Override
945 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700946 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
947 if (portStats == null) {
948 return Collections.emptyList();
949 }
950 return ImmutableList.copyOf(portStats.values());
951 }
952
953 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200954 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
955 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
956 if (portStats == null) {
957 return Collections.emptyList();
958 }
959 return ImmutableList.copyOf(portStats.values());
960 }
961
962 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700963 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
964 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
965 return ports == null ? null : ports.get(portNumber);
966 }
967
968 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700969 public PortDescription getPortDescription(ProviderId pid,
970 DeviceId deviceId,
971 PortNumber portNumber) {
972 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
973 if (descs == null) {
974 return null;
975 }
976 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
977 final Optional<DeviceDescriptions> devDescs;
978 synchronized (descs) {
979 devDescs = Optional.ofNullable(descs.get(pid));
980 }
981 // DeviceDescriptions is concurrent access-safe
982 return devDescs
983 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
984 .map(Timestamped::value)
985 .orElse(null);
986 }
987
988 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700989 public boolean isAvailable(DeviceId deviceId) {
990 return availableDevices.contains(deviceId);
991 }
992
993 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700994 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800995 final NodeId myId = clusterService.getLocalNode().id();
996 NodeId master = mastershipService.getMasterFor(deviceId);
997
998 // if there exist a master, forward
999 // if there is no master, try to become one and process
1000
1001 boolean relinquishAtEnd = false;
1002 if (master == null) {
1003 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1004 if (myRole != MastershipRole.NONE) {
1005 relinquishAtEnd = true;
1006 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001007 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001008 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001009 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -07001010 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001011 master = myId;
1012 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001013 }
1014
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001015 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001016 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001017 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001018
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001019 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001020 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001021 /* error log:
1022 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1023 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001024
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001025 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001026 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001027 }
1028
1029 // I have control..
1030
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -07001031 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001032 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001033 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001034 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001035 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001036 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001037 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001038 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001039 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001040 mastershipService.relinquishMastership(deviceId);
1041 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001042 return event;
1043 }
1044
1045 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
1046 Timestamp timestamp) {
1047
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001048 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001049 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001050 // accept removal request if given timestamp is newer than
1051 // the latest Timestamp from Primary provider
1052 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001053 if (primDescs == null) {
1054 return null;
1055 }
1056
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001057 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
1058 if (timestamp.compareTo(lastTimestamp) <= 0) {
1059 // outdated event ignore
1060 return null;
1061 }
1062 removalRequest.put(deviceId, timestamp);
1063
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001064 Device device = devices.remove(deviceId);
1065 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001066 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1067 if (ports != null) {
1068 ports.clear();
1069 }
1070 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001071 descs.clear();
1072 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001073 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001074 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001075 }
1076
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001077 /**
1078 * Checks if given timestamp is superseded by removal request
1079 * with more recent timestamp.
1080 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001081 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001082 * @param timestampToCheck timestamp of an event to check
1083 * @return true if device is already removed
1084 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001085 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1086 Timestamp removalTimestamp = removalRequest.get(deviceId);
1087 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001088 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001089 // removalRequest is more recent
1090 return true;
1091 }
1092 return false;
1093 }
1094
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001095 /**
1096 * Returns a Device, merging description given from multiple Providers.
1097 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001098 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001099 * @param providerDescs Collection of Descriptions from multiple providers
1100 * @return Device instance
1101 */
1102 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001103 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001104
Thomas Vachuska444eda62014-10-28 13:09:42 -07001105 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001106
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001107 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001108
1109 DeviceDescriptions desc = providerDescs.get(primary);
1110
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001111 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001112 Type type = base.type();
1113 String manufacturer = base.manufacturer();
1114 String hwVersion = base.hwVersion();
1115 String swVersion = base.swVersion();
1116 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001117 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001118 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1119 annotations = merge(annotations, base.annotations());
1120
1121 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1122 if (e.getKey().equals(primary)) {
1123 continue;
1124 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001125 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001126 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001127 // Currently assuming there will never be a key conflict between
1128 // providers
1129
1130 // annotation merging. not so efficient, should revisit later
1131 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1132 }
1133
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001134 return new DefaultDevice(primary, deviceId, type, manufacturer,
1135 hwVersion, swVersion, serialNumber,
1136 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001137 }
1138
Marc De Leenheer88194c32015-05-29 22:10:59 -07001139 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1140 PortDescription description, Annotations annotations) {
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001141 // FIXME this switch need to go away once all ports are done.
Marc De Leenheer88194c32015-05-29 22:10:59 -07001142 switch (description.type()) {
1143 case OMS:
HIGUCHI Yuta95d83e82016-04-26 12:13:48 -07001144 if (description instanceof OmsPortDescription) {
1145 // remove if-block once deprecation is complete
1146 OmsPortDescription omsDesc = (OmsPortDescription) description;
1147 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1148 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1149 }
1150 // same as default
1151 return new DefaultPort(device, number, isEnabled, description.type(),
1152 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001153 case OCH:
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001154 if (description instanceof OchPortDescription) {
1155 // remove if-block once Och deprecation is complete
1156 OchPortDescription ochDesc = (OchPortDescription) description;
1157 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1158 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1159 }
1160 return new DefaultPort(device, number, isEnabled, description.type(),
1161 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001162 case ODUCLT:
HIGUCHI Yuta4c0ef6b2016-05-02 19:45:41 -07001163 if (description instanceof OduCltPortDescription) {
1164 // remove if-block once deprecation is complete
1165 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1166 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1167 }
1168 // same as default
1169 return new DefaultPort(device, number, isEnabled, description.type(),
1170 description.portSpeed(), annotations);
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +02001171 case OTU:
HIGUCHI Yuta5be3e822016-05-03 13:51:42 -07001172 if (description instanceof OtuPortDescription) {
1173 // remove if-block once deprecation is complete
1174 OtuPortDescription otuDesc = (OtuPortDescription) description;
1175 return new OtuPort(device, number, isEnabled, otuDesc.signalType(), annotations);
1176 }
1177 // same as default
1178 return new DefaultPort(device, number, isEnabled, description.type(),
1179 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001180 default:
1181 return new DefaultPort(device, number, isEnabled, description.type(),
1182 description.portSpeed(), annotations);
1183 }
1184 }
1185
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001186 /**
1187 * Returns a Port, merging description given from multiple Providers.
1188 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001189 * @param device device the port is on
1190 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001191 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001192 * @return Port instance
1193 */
1194 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001195 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001196
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001197 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001198 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001199 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001200 boolean isEnabled = false;
1201 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001202 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001203 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1204 if (portDesc != null) {
1205 isEnabled = portDesc.value().isEnabled();
1206 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001207 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001208 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001209 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001210 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001211 if (e.getKey().equals(primary)) {
1212 continue;
1213 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001214 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001215 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001216 // Currently assuming there will never be a key conflict between
1217 // providers
1218
1219 // annotation merging. not so efficient, should revisit later
1220 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1221 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001222 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1223 continue;
1224 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001225 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001226 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001227 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001228 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001229 }
1230 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001231 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001232 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001233 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001234 PortDescription current = portDesc.value();
1235 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001236 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001237 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001238 }
1239
1240 /**
1241 * @return primary ProviderID, or randomly chosen one if none exists
1242 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001243 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001244 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001245 ProviderId fallBackPrimary = null;
1246 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1247 if (!e.getKey().isAncillary()) {
1248 return e.getKey();
1249 } else if (fallBackPrimary == null) {
1250 // pick randomly as a fallback in case there is no primary
1251 fallBackPrimary = e.getKey();
1252 }
1253 }
1254 return fallBackPrimary;
1255 }
1256
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001257 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001258 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001259 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001260 return providerDescs.get(pid);
1261 }
1262
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001263 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001264 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001265 }
1266
Jonathan Hart7d656f42015-01-27 14:07:23 -08001267 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001268 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001269 }
Madan Jampani47c93732014-10-06 20:46:08 -07001270
Jonathan Hart7d656f42015-01-27 14:07:23 -08001271 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001272 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001273 }
1274
Jonathan Hart7d656f42015-01-27 14:07:23 -08001275 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001276 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001277 }
1278
Jonathan Hart7d656f42015-01-27 14:07:23 -08001279 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001280 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001281 }
1282
Jonathan Hart7d656f42015-01-27 14:07:23 -08001283 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001284 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001285 }
1286
Jonathan Hart7d656f42015-01-27 14:07:23 -08001287 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001288 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1289 }
1290
1291 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1292 try {
1293 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1294 } catch (IOException e) {
1295 log.error("Failed to send" + event + " to " + recipient, e);
1296 }
1297 }
1298
1299 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1300 try {
1301 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1302 } catch (IOException e) {
1303 log.error("Failed to send" + event + " to " + recipient, e);
1304 }
1305 }
1306
1307 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1308 try {
1309 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1310 } catch (IOException e) {
1311 log.error("Failed to send" + event + " to " + recipient, e);
1312 }
1313 }
1314
1315 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1316 try {
1317 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1318 } catch (IOException e) {
1319 log.error("Failed to send" + event + " to " + recipient, e);
1320 }
1321 }
1322
1323 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1324 try {
1325 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1326 } catch (IOException e) {
1327 log.error("Failed to send" + event + " to " + recipient, e);
1328 }
1329 }
1330
1331 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1332 final NodeId self = clusterService.getLocalNode().id();
1333
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001334 final int numDevices = deviceDescs.size();
1335 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1336 final int portsPerDevice = 8; // random factor to minimize reallocation
1337 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1338 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001339
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001340 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001341
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001342 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001343 synchronized (devDescs) {
1344
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001345 // send device offline timestamp
1346 Timestamp lOffline = this.offline.get(deviceId);
1347 if (lOffline != null) {
1348 adOffline.put(deviceId, lOffline);
1349 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001350
1351 for (Entry<ProviderId, DeviceDescriptions>
1352 prov : devDescs.entrySet()) {
1353
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001354 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001355 final ProviderId provId = prov.getKey();
1356 final DeviceDescriptions descs = prov.getValue();
1357
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001358 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001359 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001360
1361 for (Entry<PortNumber, Timestamped<PortDescription>>
1362 portDesc : descs.getPortDescs().entrySet()) {
1363
1364 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001365 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001366 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001367 }
1368 }
1369 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001370 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001371
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001372 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001373 }
1374
1375 /**
1376 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001377 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001378 * Notify sender about out-dated information using regular replication message.
1379 * Send back advertisement to sender if not in sync.
1380 *
1381 * @param advertisement to respond to
1382 */
1383 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1384
1385 final NodeId sender = advertisement.sender();
1386
1387 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1388 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1389 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1390
1391 // Fragments to request
1392 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1393 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1394
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001395 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001396 final DeviceId deviceId = de.getKey();
1397 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1398
1399 synchronized (lDevice) {
1400 // latestTimestamp across provider
1401 // Note: can be null initially
1402 Timestamp localLatest = offline.get(deviceId);
1403
1404 // handle device Ads
1405 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1406 final ProviderId provId = prov.getKey();
1407 final DeviceDescriptions lDeviceDescs = prov.getValue();
1408
1409 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1410
1411
1412 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1413 Timestamp advDevTimestamp = devAds.get(devFragId);
1414
Jonathan Hart403ea932015-02-20 16:23:00 -08001415 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1416 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001417 // remote does not have it or outdated, suggest
1418 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1419 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1420 // local is outdated, request
1421 reqDevices.add(devFragId);
1422 }
1423
1424 // handle port Ads
1425 for (Entry<PortNumber, Timestamped<PortDescription>>
1426 pe : lDeviceDescs.getPortDescs().entrySet()) {
1427
1428 final PortNumber num = pe.getKey();
1429 final Timestamped<PortDescription> lPort = pe.getValue();
1430
1431 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1432
1433 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001434 if (advPortTimestamp == null || lPort.isNewerThan(
1435 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001436 // remote does not have it or outdated, suggest
1437 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1438 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1439 // local is outdated, request
1440 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1441 reqPorts.add(portFragId);
1442 }
1443
1444 // remove port Ad already processed
1445 portAds.remove(portFragId);
1446 } // end local port loop
1447
1448 // remove device Ad already processed
1449 devAds.remove(devFragId);
1450
1451 // find latest and update
1452 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1453 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001454 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001455 localLatest = providerLatest;
1456 }
1457 } // end local provider loop
1458
1459 // checking if remote timestamp is more recent.
1460 Timestamp rOffline = offlineAds.get(deviceId);
1461 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001462 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001463 // remote offline timestamp suggests that the
1464 // device is off-line
1465 markOfflineInternal(deviceId, rOffline);
1466 }
1467
1468 Timestamp lOffline = offline.get(deviceId);
1469 if (lOffline != null && rOffline == null) {
1470 // locally offline, but remote is online, suggest offline
1471 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1472 }
1473
1474 // remove device offline Ad already processed
1475 offlineAds.remove(deviceId);
1476 } // end local device loop
1477 } // device lock
1478
1479 // If there is any Ads left, request them
1480 log.trace("Ads left {}, {}", devAds, portAds);
1481 reqDevices.addAll(devAds.keySet());
1482 reqPorts.addAll(portAds.keySet());
1483
1484 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1485 log.trace("Nothing to request to remote peer {}", sender);
1486 return;
1487 }
1488
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001489 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001490
1491 // 2-way Anti-Entropy for now
1492 try {
1493 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1494 } catch (IOException e) {
1495 log.error("Failed to send response advertisement to " + sender, e);
1496 }
1497
1498// Sketch of 3-way Anti-Entropy
1499// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1500// ClusterMessage message = new ClusterMessage(
1501// clusterService.getLocalNode().id(),
1502// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1503// SERIALIZER.encode(request));
1504//
1505// try {
1506// clusterCommunicator.unicast(message, advertisement.sender());
1507// } catch (IOException e) {
1508// log.error("Failed to send advertisement reply to "
1509// + advertisement.sender(), e);
1510// }
Madan Jampani47c93732014-10-06 20:46:08 -07001511 }
1512
Madan Jampani255a58b2014-10-09 12:08:20 -07001513 private void notifyDelegateIfNotNull(DeviceEvent event) {
1514 if (event != null) {
1515 notifyDelegate(event);
1516 }
1517 }
1518
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001519 private final class SendAdvertisementTask implements Runnable {
1520
1521 @Override
1522 public void run() {
1523 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001524 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001525 return;
1526 }
1527
1528 try {
1529 final NodeId self = clusterService.getLocalNode().id();
1530 Set<ControllerNode> nodes = clusterService.getNodes();
1531
1532 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1533 .transform(toNodeId())
1534 .toList();
1535
1536 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001537 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001538 return;
1539 }
1540
1541 NodeId peer;
1542 do {
1543 int idx = RandomUtils.nextInt(0, nodeIds.size());
1544 peer = nodeIds.get(idx);
1545 } while (peer.equals(self));
1546
1547 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1548
1549 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001550 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001551 return;
1552 }
1553
1554 try {
1555 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1556 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001557 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001558 return;
1559 }
1560 } catch (Exception e) {
1561 // catch all Exception to avoid Scheduled task being suppressed.
1562 log.error("Exception thrown while sending advertisement", e);
1563 }
1564 }
1565 }
1566
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001567 private final class InternalDeviceEventListener
1568 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001569 @Override
1570 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001571 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001572 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001573
Madan Jampani47c93732014-10-06 20:46:08 -07001574 ProviderId providerId = event.providerId();
1575 DeviceId deviceId = event.deviceId();
1576 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001577
Madan Jampani2af244a2015-02-22 13:12:01 -08001578 try {
1579 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1580 } catch (Exception e) {
1581 log.warn("Exception thrown handling device update", e);
1582 }
Madan Jampani47c93732014-10-06 20:46:08 -07001583 }
1584 }
1585
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001586 private final class InternalDeviceOfflineEventListener
1587 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001588 @Override
1589 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001590 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001591 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001592
1593 DeviceId deviceId = event.deviceId();
1594 Timestamp timestamp = event.timestamp();
1595
Madan Jampani2af244a2015-02-22 13:12:01 -08001596 try {
1597 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1598 } catch (Exception e) {
1599 log.warn("Exception thrown handling device offline", e);
1600 }
Madan Jampani25322532014-10-08 11:20:38 -07001601 }
1602 }
1603
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001604 private final class InternalRemoveRequestListener
1605 implements ClusterMessageHandler {
1606 @Override
1607 public void handle(ClusterMessage message) {
1608 log.debug("Received device remove request from peer: {}", message.sender());
1609 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001610
Madan Jampani2af244a2015-02-22 13:12:01 -08001611 try {
1612 removeDevice(did);
1613 } catch (Exception e) {
1614 log.warn("Exception thrown handling device remove", e);
1615 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001616 }
1617 }
1618
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001619 private final class InternalDeviceRemovedEventListener
1620 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001621 @Override
1622 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001623 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001624 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001625
1626 DeviceId deviceId = event.deviceId();
1627 Timestamp timestamp = event.timestamp();
1628
Madan Jampani2af244a2015-02-22 13:12:01 -08001629 try {
1630 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1631 } catch (Exception e) {
1632 log.warn("Exception thrown handling device removed", e);
1633 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001634 }
1635 }
1636
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001637 private final class InternalPortEventListener
1638 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001639 @Override
1640 public void handle(ClusterMessage message) {
1641
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001642 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001643 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001644
1645 ProviderId providerId = event.providerId();
1646 DeviceId deviceId = event.deviceId();
1647 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1648
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001649 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001650 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001651 // Note: dropped information will be recovered by anti-entropy
1652 return;
1653 }
1654
Madan Jampani2af244a2015-02-22 13:12:01 -08001655 try {
1656 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1657 } catch (Exception e) {
1658 log.warn("Exception thrown handling port update", e);
1659 }
Madan Jampani47c93732014-10-06 20:46:08 -07001660 }
1661 }
1662
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001663 private final class InternalPortStatusEventListener
1664 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001665 @Override
1666 public void handle(ClusterMessage message) {
1667
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001668 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001669 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001670
1671 ProviderId providerId = event.providerId();
1672 DeviceId deviceId = event.deviceId();
1673 Timestamped<PortDescription> portDescription = event.portDescription();
1674
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001675 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001676 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001677 // Note: dropped information will be recovered by anti-entropy
1678 return;
1679 }
1680
Madan Jampani2af244a2015-02-22 13:12:01 -08001681 try {
1682 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1683 } catch (Exception e) {
1684 log.warn("Exception thrown handling port update", e);
1685 }
Madan Jampani47c93732014-10-06 20:46:08 -07001686 }
1687 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001688
1689 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001690 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001691 @Override
1692 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001693 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001694 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001695 try {
1696 handleAdvertisement(advertisement);
1697 } catch (Exception e) {
1698 log.warn("Exception thrown handling Device advertisements.", e);
1699 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001700 }
1701 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001702
1703 private final class DeviceInjectedEventListener
1704 implements ClusterMessageHandler {
1705 @Override
1706 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001707 log.debug("Received injected device event from peer: {}", message.sender());
1708 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1709
1710 ProviderId providerId = event.providerId();
1711 DeviceId deviceId = event.deviceId();
1712 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001713 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1714 // workaround for ONOS-1208
1715 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1716 return;
1717 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001718
Madan Jampani2af244a2015-02-22 13:12:01 -08001719 try {
1720 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1721 } catch (Exception e) {
1722 log.warn("Exception thrown handling device injected event.", e);
1723 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001724 }
1725 }
1726
1727 private final class PortInjectedEventListener
1728 implements ClusterMessageHandler {
1729 @Override
1730 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001731 log.debug("Received injected port event from peer: {}", message.sender());
1732 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1733
1734 ProviderId providerId = event.providerId();
1735 DeviceId deviceId = event.deviceId();
1736 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001737 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1738 // workaround for ONOS-1208
1739 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1740 return;
1741 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001742
Madan Jampani2af244a2015-02-22 13:12:01 -08001743 try {
1744 updatePorts(providerId, deviceId, portDescriptions);
1745 } catch (Exception e) {
1746 log.warn("Exception thrown handling port injected event.", e);
1747 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001748 }
1749 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001750
1751 private class InternalPortStatsListener
1752 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1753 @Override
1754 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1755 if (event.type() == PUT) {
1756 Device device = devices.get(event.key());
1757 if (device != null) {
1758 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1759 }
1760 }
1761 }
1762 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001763}