blob: e6d645f08202fdb35da8ce2e20ea62e25d7037be [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;
Brian O'Connorabafb502014-12-02 22:26:20 -080075import org.onosproject.store.serializers.KryoSerializer;
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;
96import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070097import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080098import java.util.concurrent.ExecutorService;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070099import java.util.concurrent.ScheduledExecutorService;
100import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700101
102import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700103import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700104import static com.google.common.base.Verify.verify;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800105import static java.util.concurrent.Executors.newCachedThreadPool;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800106import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
107import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800108import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800109import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800110import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
111import static org.onosproject.net.DefaultAnnotations.merge;
112import static org.onosproject.net.device.DeviceEvent.Type.*;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800113import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700114import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800115import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700116
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700117/**
118 * Manages inventory of infrastructure devices using gossip protocol to distribute
119 * information.
120 */
121@Component(immediate = true)
122@Service
123public class GossipDeviceStore
124 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
125 implements DeviceStore {
126
127 private final Logger log = getLogger(getClass());
128
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700129 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800130 // Timeout in milliseconds to process device or ports on remote master node
131 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700132
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700133 // innerMap is used to lock a Device, thus instance should never be replaced.
134 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700135 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700136 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700137
138 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700139 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
140 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700141
142 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200143 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700144 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
145 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700146
147 // to be updated under Device lock
148 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
149 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700150
151 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700152 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700153
154 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700155 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700156
Madan Jampani47c93732014-10-06 20:46:08 -0700157 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700158 protected StorageService storageService;
159
160 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700161 protected ClusterCommunicationService clusterCommunicator;
162
Madan Jampani53e44e62014-10-07 12:39:51 -0700163 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
164 protected ClusterService clusterService;
165
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700166 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
167 protected MastershipService mastershipService;
168
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800169 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
170 protected MastershipTermService termService;
171
172
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700173 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700174 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700175 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700176 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800177 .register(DistributedStoreSerializers.STORE_COMMON)
178 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
179 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
180 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700181 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800182 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
183 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700184 .register(DeviceAntiEntropyAdvertisement.class)
185 .register(DeviceFragmentId.class)
186 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800187 .register(DeviceInjectedEvent.class)
188 .register(PortInjectedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800189 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700190 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700191 };
192
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800193 private ExecutorService executor;
194
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800195 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700196
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800197 // TODO make these anti-entropy parameters configurable
198 private long initialDelaySec = 5;
199 private long periodSec = 5;
200
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700201 @Activate
202 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800203 executor = newCachedThreadPool(groupedThreads("onos/device", "fg-%d", log));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800204
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800205 backgroundExecutor =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800206 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d", log)));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700207
Madan Jampani2af244a2015-02-22 13:12:01 -0800208 clusterCommunicator.addSubscriber(
209 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
210 clusterCommunicator.addSubscriber(
211 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
212 new InternalDeviceOfflineEventListener(),
213 executor);
214 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700215 new InternalRemoveRequestListener(),
216 executor);
Madan Jampani2af244a2015-02-22 13:12:01 -0800217 clusterCommunicator.addSubscriber(
218 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
219 clusterCommunicator.addSubscriber(
220 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
221 clusterCommunicator.addSubscriber(
222 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
223 clusterCommunicator.addSubscriber(
224 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
225 new InternalDeviceAdvertisementListener(),
226 backgroundExecutor);
227 clusterCommunicator.addSubscriber(
228 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
229 clusterCommunicator.addSubscriber(
230 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
231
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700232 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800233 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700234 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700235
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700236 // Create a distributed map for port stats.
237 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
238 .register(KryoNamespaces.API)
239 .register(DefaultPortStatistics.class)
240 .register(DeviceId.class)
241 .register(MultiValuedTimestamp.class)
242 .register(WallClockTimestamp.class);
243
244 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
245 .withName("port-stats")
246 .withSerializer(deviceDataSerializer)
247 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700248 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700249 .withTombstonesDisabled()
250 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200251 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
252 eventuallyConsistentMapBuilder()
253 .withName("port-stats-delta")
254 .withSerializer(deviceDataSerializer)
255 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
256 .withTimestampProvider((k, v) -> new WallClockTimestamp())
257 .withTombstonesDisabled()
258 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700259 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700260 log.info("Started");
261 }
262
263 @Deactivate
264 public void deactivate() {
Madan Jampani632f16b2015-08-11 12:42:59 -0700265 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200266 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800267 executor.shutdownNow();
268
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800269 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700270 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800271 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700272 log.error("Timeout during executor shutdown");
273 }
274 } catch (InterruptedException e) {
275 log.error("Error during executor shutdown", e);
276 }
277
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700278 deviceDescs.clear();
279 devices.clear();
280 devicePorts.clear();
281 availableDevices.clear();
282 log.info("Stopped");
283 }
284
285 @Override
286 public int getDeviceCount() {
287 return devices.size();
288 }
289
290 @Override
291 public Iterable<Device> getDevices() {
292 return Collections.unmodifiableCollection(devices.values());
293 }
294
295 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800296 public Iterable<Device> getAvailableDevices() {
297 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700298 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800299 }
300
301 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700302 public Device getDevice(DeviceId deviceId) {
303 return devices.get(deviceId);
304 }
305
306 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700307 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700308 DeviceId deviceId,
309 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800310 NodeId localNode = clusterService.getLocalNode().id();
311 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
312
313 // Process device update only if we're the master,
314 // otherwise signal the actual master.
315 DeviceEvent deviceEvent = null;
316 if (localNode.equals(deviceNode)) {
317
318 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
319 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
320 final Timestamped<DeviceDescription> mergedDesc;
321 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
322
323 synchronized (device) {
324 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
325 mergedDesc = device.get(providerId).getDeviceDesc();
326 }
327
328 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700329 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700330 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800331 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
332 }
333
334 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800335 // Only forward for ConfigProvider
336 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800337 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800338 return null;
339 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800340 // FIXME Temporary hack for NPE (ONOS-1171).
341 // Proper fix is to implement forwarding to master on ConfigProvider
342 // redo ONOS-490
343 if (deviceNode == null) {
344 // silently ignore
345 return null;
346 }
347
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800348
349 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
350 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800351
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800352 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700353 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800354 /* error log:
355 log.warn("Failed to process injected device id: {} desc: {} " +
356 "(cluster messaging failed: {})",
357 deviceId, deviceDescription, e);
358 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700359 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800360
361 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700362 }
363
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700364 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700365 DeviceId deviceId,
366 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700367
368 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800369 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700370 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700371
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800372 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700373 // locking per device
374
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700375 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
376 log.debug("Ignoring outdated event: {}", deltaDesc);
377 return null;
378 }
379
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800380 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700381
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700382 final Device oldDevice = devices.get(deviceId);
383 final Device newDevice;
384
385 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700386 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700387 // on new device or valid update
388 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800389 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700390 } else {
391 // outdated event, ignored.
392 return null;
393 }
394 if (oldDevice == null) {
395 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700396 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700397 } else {
398 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700399 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700400 }
401 }
402 }
403
404 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700405 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700406 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700407 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700408
409 // update composed device cache
410 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
411 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700412 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
413 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700414
415 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700416 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700417 }
418
419 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
420 }
421
422 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700423 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700424 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700425 Device oldDevice,
426 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700427 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700428 boolean propertiesChanged =
429 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700430 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
431 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700432 boolean annotationsChanged =
433 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700434
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700435 // Primary providers can respond to all changes, but ancillary ones
436 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800437 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700438 if ((providerId.isAncillary() && annotationsChanged) ||
439 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700440 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
441 if (!replaced) {
442 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700443 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800444 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700445 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700446
alshabibdc5d8bd2015-11-02 15:41:29 -0800447 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700448 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800449
450 if (!providerId.isAncillary()) {
451 boolean wasOnline = availableDevices.contains(newDevice.id());
452 markOnline(newDevice.id(), newTimestamp);
453 if (!wasOnline) {
454 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
455 }
456 }
457 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700458 }
459
460 @Override
461 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700462 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700463 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700464 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700465 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700466 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800467 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700468 }
469 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700470 }
471
472 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
473
474 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700475 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700476
477 // locking device
478 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700479
480 // accept off-line if given timestamp is newer than
481 // the latest Timestamp from Primary provider
482 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
483 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
484 if (timestamp.compareTo(lastTimestamp) <= 0) {
485 // outdated event ignore
486 return null;
487 }
488
489 offline.put(deviceId, timestamp);
490
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700491 Device device = devices.get(deviceId);
492 if (device == null) {
493 return null;
494 }
495 boolean removed = availableDevices.remove(deviceId);
496 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700497 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700498 }
499 return null;
500 }
501 }
502
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700503 /**
504 * Marks the device as available if the given timestamp is not outdated,
505 * compared to the time the device has been marked offline.
506 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700507 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700508 * @param timestamp of the event triggering this change.
509 * @return true if availability change request was accepted and changed the state
510 */
511 // Guarded by deviceDescs value (=Device lock)
512 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
513 // accept on-line if given timestamp is newer than
514 // the latest offline request Timestamp
515 Timestamp offlineTimestamp = offline.get(deviceId);
516 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700517 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700518
519 offline.remove(deviceId);
520 return availableDevices.add(deviceId);
521 }
522 return false;
523 }
524
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700525 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700526 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700527 DeviceId deviceId,
528 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700529
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800530 NodeId localNode = clusterService.getLocalNode().id();
531 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
532 // since it will trigger distributed store read.
533 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
534 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
535 // If we don't care much about topology performance, then it might be OK.
536 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700537
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800538 // Process port update only if we're the master of the device,
539 // otherwise signal the actual master.
540 List<DeviceEvent> deviceEvents = null;
541 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700542
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800543 final Timestamp newTimestamp;
544 try {
545 newTimestamp = deviceClockService.getTimestamp(deviceId);
546 } catch (IllegalStateException e) {
547 log.info("Timestamp was not available for device {}", deviceId);
548 log.debug(" discarding {}", portDescriptions);
549 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700550
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800551 // Possible situation:
552 // Device connected and became master for short period of time,
553 // but lost mastership before this instance had the chance to
554 // retrieve term information.
555
556 // Information dropped here is expected to be recoverable by
557 // device probing after mastership change
558
559 return Collections.emptyList();
560 }
561 log.debug("timestamp for {} {}", deviceId, newTimestamp);
562
563 final Timestamped<List<PortDescription>> timestampedInput
564 = new Timestamped<>(portDescriptions, newTimestamp);
565 final Timestamped<List<PortDescription>> merged;
566
567 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
568
569 synchronized (device) {
570 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
571 final DeviceDescriptions descs = device.get(providerId);
572 List<PortDescription> mergedList =
573 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700574 .transform(input ->
575 // lookup merged port description
576 descs.getPortDesc(input.portNumber()).value()
577 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700578 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800579 }
580
581 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700582 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700583 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800584 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
585 }
586
587 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800588 // Only forward for ConfigProvider
589 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800590 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta89461772016-01-26 12:18:10 -0800591 return Collections.emptyList();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800592 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800593 // FIXME Temporary hack for NPE (ONOS-1171).
594 // Proper fix is to implement forwarding to master on ConfigProvider
595 // redo ONOS-490
596 if (deviceNode == null) {
597 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800598 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800599 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800600
601 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800602
603 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700604 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800605 /* error log:
606 log.warn("Failed to process injected ports of device id: {} " +
607 "(cluster messaging failed: {})",
608 deviceId, e);
609 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700610 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700611
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800612 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700613 }
614
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700615 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700616 DeviceId deviceId,
617 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700618
619 Device device = devices.get(deviceId);
620 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
621
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700622 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700623 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
624
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700625 List<DeviceEvent> events = new ArrayList<>();
626 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700627
628 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
629 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700630 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700631 }
632
633 DeviceDescriptions descs = descsMap.get(providerId);
634 // every provider must provide DeviceDescription.
635 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700636 "Device description for Device ID %s from Provider %s was not found",
637 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700638
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700639 Map<PortNumber, Port> ports = getPortMap(deviceId);
640
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700641 final Timestamp newTimestamp = portDescriptions.timestamp();
642
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700643 // Add new ports
644 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700645 for (PortDescription portDescription : portDescriptions.value()) {
646 final PortNumber number = portDescription.portNumber();
647 processed.add(number);
648
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700649 final Port oldPort = ports.get(number);
650 final Port newPort;
651
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700652
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700653 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
654 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700655 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700656 // on new port or valid update
657 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700658 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700659 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700660 newPort = composePort(device, number, descsMap);
661 } else {
662 // outdated event, ignored.
663 continue;
664 }
665
666 events.add(oldPort == null ?
667 createPort(device, newPort, ports) :
668 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700669 }
670
671 events.addAll(pruneOldPorts(device, ports, processed));
672 }
673 return FluentIterable.from(events).filter(notNull()).toList();
674 }
675
676 // Creates a new port based on the port description adds it to the map and
677 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700678 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700679 private DeviceEvent createPort(Device device, Port newPort,
680 Map<PortNumber, Port> ports) {
681 ports.put(newPort.number(), newPort);
682 return new DeviceEvent(PORT_ADDED, device, newPort);
683 }
684
685 // Checks if the specified port requires update and if so, it replaces the
686 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700687 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700688 private DeviceEvent updatePort(Device device, Port oldPort,
689 Port newPort,
690 Map<PortNumber, Port> ports) {
691 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700692 oldPort.type() != newPort.type() ||
693 oldPort.portSpeed() != newPort.portSpeed() ||
694 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700695 ports.put(oldPort.number(), newPort);
696 return new DeviceEvent(PORT_UPDATED, device, newPort);
697 }
698 return null;
699 }
700
701 // Prunes the specified list of ports based on which ports are in the
702 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700703 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700704 private List<DeviceEvent> pruneOldPorts(Device device,
705 Map<PortNumber, Port> ports,
706 Set<PortNumber> processed) {
707 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700708 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700709 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700710 Entry<PortNumber, Port> e = iterator.next();
711 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700712 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700713 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700714 iterator.remove();
715 }
716 }
717 return events;
718 }
719
720 // Gets the map of ports for the specified device; if one does not already
721 // exist, it creates and registers a new one.
722 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
723 return createIfAbsentUnchecked(devicePorts, deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700724 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700725 }
726
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700727 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700728 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700729 Map<ProviderId, DeviceDescriptions> r;
730 r = deviceDescs.get(deviceId);
731 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700732 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700733 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
734 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
735 if (concurrentlyAdded != null) {
736 r = concurrentlyAdded;
737 }
738 }
739 return r;
740 }
741
742 // Guarded by deviceDescs value (=Device lock)
743 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
744 Map<ProviderId, DeviceDescriptions> device,
745 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700746 synchronized (device) {
747 DeviceDescriptions r = device.get(providerId);
748 if (r == null) {
749 r = new DeviceDescriptions(deltaDesc);
750 device.put(providerId, r);
751 }
752 return r;
753 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700754 }
755
756 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700757 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
758 DeviceId deviceId,
759 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700760 final Timestamp newTimestamp;
761 try {
762 newTimestamp = deviceClockService.getTimestamp(deviceId);
763 } catch (IllegalStateException e) {
764 log.info("Timestamp was not available for device {}", deviceId);
765 log.debug(" discarding {}", portDescription);
766 // Failed to generate timestamp. Ignoring.
767 // See updatePorts comment
768 return null;
769 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700770 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700771 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700772 final DeviceEvent event;
773 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800774 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
775 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700776 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800777 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700778 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700779 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700780 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700781 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700782 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800783 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700784 }
785 return event;
786 }
787
788 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700789 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700790 Device device = devices.get(deviceId);
791 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
792
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700793 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700794 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
795
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700796 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700797
798 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
799 log.debug("Ignoring outdated event: {}", deltaDesc);
800 return null;
801 }
802
803 DeviceDescriptions descs = descsMap.get(providerId);
804 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700805 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700806 "Device description for Device ID %s from Provider %s was not found",
807 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700808
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700809 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
810 final PortNumber number = deltaDesc.value().portNumber();
811 final Port oldPort = ports.get(number);
812 final Port newPort;
813
814 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
815 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700816 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700817 // on new port or valid update
818 // update description
819 descs.putPortDesc(deltaDesc);
820 newPort = composePort(device, number, descsMap);
821 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700822 // same or outdated event, ignored.
823 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700824 return null;
825 }
826
827 if (oldPort == null) {
828 return createPort(device, newPort, ports);
829 } else {
830 return updatePort(device, oldPort, newPort, ports);
831 }
832 }
833 }
834
835 @Override
836 public List<Port> getPorts(DeviceId deviceId) {
837 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
838 if (ports == null) {
839 return Collections.emptyList();
840 }
841 return ImmutableList.copyOf(ports.values());
842 }
843
844 @Override
sangho538108b2015-04-08 14:29:20 -0700845 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200846 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700847
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200848 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
849 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
850 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
851
852 if (prvStatsMap != null) {
853 for (PortStatistics newStats : newStatsCollection) {
854 PortNumber port = PortNumber.portNumber(newStats.port());
855 PortStatistics prvStats = prvStatsMap.get(port);
856 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
857 PortStatistics deltaStats = builder.build();
858 if (prvStats != null) {
859 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
860 }
861 deltaStatsMap.put(port, deltaStats);
862 newStatsMap.put(port, newStats);
863 }
864 } else {
865 for (PortStatistics newStats : newStatsCollection) {
866 PortNumber port = PortNumber.portNumber(newStats.port());
867 newStatsMap.put(port, newStats);
868 }
sangho538108b2015-04-08 14:29:20 -0700869 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200870 devicePortDeltaStats.put(deviceId, deltaStatsMap);
871 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200872 // DeviceEvent returns null because of InternalPortStatsListener usage
873 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200874 }
875
876 /**
877 * Calculate delta statistics by subtracting previous from new statistics.
878 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700879 * @param deviceId device identifier
880 * @param prvStats previous port statistics
881 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200882 * @return PortStatistics
883 */
884 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
885 // calculate time difference
886 long deltaStatsSec, deltaStatsNano;
887 if (newStats.durationNano() < prvStats.durationNano()) {
888 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
889 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
890 } else {
891 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
892 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
893 }
894 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
895 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
896 .setPort(newStats.port())
897 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
898 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
899 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
900 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
901 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
902 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
903 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
904 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
905 .setDurationSec(deltaStatsSec)
906 .setDurationNano(deltaStatsNano)
907 .build();
908 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700909 }
910
911 @Override
912 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700913 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
914 if (portStats == null) {
915 return Collections.emptyList();
916 }
917 return ImmutableList.copyOf(portStats.values());
918 }
919
920 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200921 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
922 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
923 if (portStats == null) {
924 return Collections.emptyList();
925 }
926 return ImmutableList.copyOf(portStats.values());
927 }
928
929 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700930 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
931 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
932 return ports == null ? null : ports.get(portNumber);
933 }
934
935 @Override
936 public boolean isAvailable(DeviceId deviceId) {
937 return availableDevices.contains(deviceId);
938 }
939
940 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700941 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800942 final NodeId myId = clusterService.getLocalNode().id();
943 NodeId master = mastershipService.getMasterFor(deviceId);
944
945 // if there exist a master, forward
946 // if there is no master, try to become one and process
947
948 boolean relinquishAtEnd = false;
949 if (master == null) {
950 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
951 if (myRole != MastershipRole.NONE) {
952 relinquishAtEnd = true;
953 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800954 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800955 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800956 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700957 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800958 master = myId;
959 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700960 }
961
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800962 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800963 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700964 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800965
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800966 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700967 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800968 /* error log:
969 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
970 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800971
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800972 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700973 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800974 }
975
976 // I have control..
977
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700978 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700979 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700980 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800981 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700982 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800983 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700984 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800985 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800986 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800987 mastershipService.relinquishMastership(deviceId);
988 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700989 return event;
990 }
991
992 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
993 Timestamp timestamp) {
994
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700995 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700996 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700997 // accept removal request if given timestamp is newer than
998 // the latest Timestamp from Primary provider
999 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001000 if (primDescs == null) {
1001 return null;
1002 }
1003
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001004 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
1005 if (timestamp.compareTo(lastTimestamp) <= 0) {
1006 // outdated event ignore
1007 return null;
1008 }
1009 removalRequest.put(deviceId, timestamp);
1010
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001011 Device device = devices.remove(deviceId);
1012 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001013 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1014 if (ports != null) {
1015 ports.clear();
1016 }
1017 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001018 descs.clear();
1019 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001020 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001021 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001022 }
1023
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001024 /**
1025 * Checks if given timestamp is superseded by removal request
1026 * with more recent timestamp.
1027 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001028 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001029 * @param timestampToCheck timestamp of an event to check
1030 * @return true if device is already removed
1031 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001032 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1033 Timestamp removalTimestamp = removalRequest.get(deviceId);
1034 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001035 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001036 // removalRequest is more recent
1037 return true;
1038 }
1039 return false;
1040 }
1041
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001042 /**
1043 * Returns a Device, merging description given from multiple Providers.
1044 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001045 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001046 * @param providerDescs Collection of Descriptions from multiple providers
1047 * @return Device instance
1048 */
1049 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001050 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001051
Thomas Vachuska444eda62014-10-28 13:09:42 -07001052 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001053
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001054 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001055
1056 DeviceDescriptions desc = providerDescs.get(primary);
1057
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001058 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001059 Type type = base.type();
1060 String manufacturer = base.manufacturer();
1061 String hwVersion = base.hwVersion();
1062 String swVersion = base.swVersion();
1063 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001064 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001065 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1066 annotations = merge(annotations, base.annotations());
1067
1068 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1069 if (e.getKey().equals(primary)) {
1070 continue;
1071 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001072 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001073 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001074 // Currently assuming there will never be a key conflict between
1075 // providers
1076
1077 // annotation merging. not so efficient, should revisit later
1078 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1079 }
1080
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001081 return new DefaultDevice(primary, deviceId, type, manufacturer,
1082 hwVersion, swVersion, serialNumber,
1083 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001084 }
1085
Marc De Leenheer88194c32015-05-29 22:10:59 -07001086 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1087 PortDescription description, Annotations annotations) {
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001088 // FIXME this switch need to go away once all ports are done.
Marc De Leenheer88194c32015-05-29 22:10:59 -07001089 switch (description.type()) {
1090 case OMS:
HIGUCHI Yuta95d83e82016-04-26 12:13:48 -07001091 if (description instanceof OmsPortDescription) {
1092 // remove if-block once deprecation is complete
1093 OmsPortDescription omsDesc = (OmsPortDescription) description;
1094 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1095 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1096 }
1097 // same as default
1098 return new DefaultPort(device, number, isEnabled, description.type(),
1099 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001100 case OCH:
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001101 if (description instanceof OchPortDescription) {
1102 // remove if-block once Och deprecation is complete
1103 OchPortDescription ochDesc = (OchPortDescription) description;
1104 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1105 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1106 }
1107 return new DefaultPort(device, number, isEnabled, description.type(),
1108 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001109 case ODUCLT:
1110 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1111 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +02001112 case OTU:
1113 OtuPortDescription otuDesc = (OtuPortDescription) description;
1114 return new OtuPort(device, number, isEnabled, otuDesc.signalType(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001115 default:
1116 return new DefaultPort(device, number, isEnabled, description.type(),
1117 description.portSpeed(), annotations);
1118 }
1119 }
1120
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001121 /**
1122 * Returns a Port, merging description given from multiple Providers.
1123 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001124 * @param device device the port is on
1125 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001126 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001127 * @return Port instance
1128 */
1129 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001130 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001131
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001132 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001133 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001134 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001135 boolean isEnabled = false;
1136 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001137 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001138 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1139 if (portDesc != null) {
1140 isEnabled = portDesc.value().isEnabled();
1141 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001142 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001143 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001144 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001145 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001146 if (e.getKey().equals(primary)) {
1147 continue;
1148 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001149 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001150 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001151 // Currently assuming there will never be a key conflict between
1152 // providers
1153
1154 // annotation merging. not so efficient, should revisit later
1155 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1156 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001157 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1158 continue;
1159 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001160 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001161 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001162 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001163 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001164 }
1165 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001166 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001167 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001168 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001169 PortDescription current = portDesc.value();
1170 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001171 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001172 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001173 }
1174
1175 /**
1176 * @return primary ProviderID, or randomly chosen one if none exists
1177 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001178 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001179 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001180 ProviderId fallBackPrimary = null;
1181 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1182 if (!e.getKey().isAncillary()) {
1183 return e.getKey();
1184 } else if (fallBackPrimary == null) {
1185 // pick randomly as a fallback in case there is no primary
1186 fallBackPrimary = e.getKey();
1187 }
1188 }
1189 return fallBackPrimary;
1190 }
1191
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001192 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001193 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001194 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001195 return providerDescs.get(pid);
1196 }
1197
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001198 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001199 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001200 }
1201
Jonathan Hart7d656f42015-01-27 14:07:23 -08001202 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001203 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001204 }
Madan Jampani47c93732014-10-06 20:46:08 -07001205
Jonathan Hart7d656f42015-01-27 14:07:23 -08001206 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001207 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001208 }
1209
Jonathan Hart7d656f42015-01-27 14:07:23 -08001210 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001211 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001212 }
1213
Jonathan Hart7d656f42015-01-27 14:07:23 -08001214 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001215 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001216 }
1217
Jonathan Hart7d656f42015-01-27 14:07:23 -08001218 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001219 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001220 }
1221
Jonathan Hart7d656f42015-01-27 14:07:23 -08001222 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001223 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1224 }
1225
1226 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1227 try {
1228 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1229 } catch (IOException e) {
1230 log.error("Failed to send" + event + " to " + recipient, e);
1231 }
1232 }
1233
1234 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1235 try {
1236 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1237 } catch (IOException e) {
1238 log.error("Failed to send" + event + " to " + recipient, e);
1239 }
1240 }
1241
1242 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1243 try {
1244 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1245 } catch (IOException e) {
1246 log.error("Failed to send" + event + " to " + recipient, e);
1247 }
1248 }
1249
1250 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1251 try {
1252 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1253 } catch (IOException e) {
1254 log.error("Failed to send" + event + " to " + recipient, e);
1255 }
1256 }
1257
1258 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1259 try {
1260 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1261 } catch (IOException e) {
1262 log.error("Failed to send" + event + " to " + recipient, e);
1263 }
1264 }
1265
1266 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1267 final NodeId self = clusterService.getLocalNode().id();
1268
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001269 final int numDevices = deviceDescs.size();
1270 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1271 final int portsPerDevice = 8; // random factor to minimize reallocation
1272 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1273 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001274
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001275 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001276
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001277 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001278 synchronized (devDescs) {
1279
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001280 // send device offline timestamp
1281 Timestamp lOffline = this.offline.get(deviceId);
1282 if (lOffline != null) {
1283 adOffline.put(deviceId, lOffline);
1284 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001285
1286 for (Entry<ProviderId, DeviceDescriptions>
1287 prov : devDescs.entrySet()) {
1288
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001289 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001290 final ProviderId provId = prov.getKey();
1291 final DeviceDescriptions descs = prov.getValue();
1292
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001293 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001294 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001295
1296 for (Entry<PortNumber, Timestamped<PortDescription>>
1297 portDesc : descs.getPortDescs().entrySet()) {
1298
1299 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001300 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001301 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001302 }
1303 }
1304 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001305 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001306
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001307 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001308 }
1309
1310 /**
1311 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001312 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001313 * Notify sender about out-dated information using regular replication message.
1314 * Send back advertisement to sender if not in sync.
1315 *
1316 * @param advertisement to respond to
1317 */
1318 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1319
1320 final NodeId sender = advertisement.sender();
1321
1322 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1323 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1324 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1325
1326 // Fragments to request
1327 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1328 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1329
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001330 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001331 final DeviceId deviceId = de.getKey();
1332 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1333
1334 synchronized (lDevice) {
1335 // latestTimestamp across provider
1336 // Note: can be null initially
1337 Timestamp localLatest = offline.get(deviceId);
1338
1339 // handle device Ads
1340 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1341 final ProviderId provId = prov.getKey();
1342 final DeviceDescriptions lDeviceDescs = prov.getValue();
1343
1344 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1345
1346
1347 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1348 Timestamp advDevTimestamp = devAds.get(devFragId);
1349
Jonathan Hart403ea932015-02-20 16:23:00 -08001350 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1351 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001352 // remote does not have it or outdated, suggest
1353 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1354 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1355 // local is outdated, request
1356 reqDevices.add(devFragId);
1357 }
1358
1359 // handle port Ads
1360 for (Entry<PortNumber, Timestamped<PortDescription>>
1361 pe : lDeviceDescs.getPortDescs().entrySet()) {
1362
1363 final PortNumber num = pe.getKey();
1364 final Timestamped<PortDescription> lPort = pe.getValue();
1365
1366 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1367
1368 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001369 if (advPortTimestamp == null || lPort.isNewerThan(
1370 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001371 // remote does not have it or outdated, suggest
1372 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1373 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1374 // local is outdated, request
1375 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1376 reqPorts.add(portFragId);
1377 }
1378
1379 // remove port Ad already processed
1380 portAds.remove(portFragId);
1381 } // end local port loop
1382
1383 // remove device Ad already processed
1384 devAds.remove(devFragId);
1385
1386 // find latest and update
1387 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1388 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001389 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001390 localLatest = providerLatest;
1391 }
1392 } // end local provider loop
1393
1394 // checking if remote timestamp is more recent.
1395 Timestamp rOffline = offlineAds.get(deviceId);
1396 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001397 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001398 // remote offline timestamp suggests that the
1399 // device is off-line
1400 markOfflineInternal(deviceId, rOffline);
1401 }
1402
1403 Timestamp lOffline = offline.get(deviceId);
1404 if (lOffline != null && rOffline == null) {
1405 // locally offline, but remote is online, suggest offline
1406 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1407 }
1408
1409 // remove device offline Ad already processed
1410 offlineAds.remove(deviceId);
1411 } // end local device loop
1412 } // device lock
1413
1414 // If there is any Ads left, request them
1415 log.trace("Ads left {}, {}", devAds, portAds);
1416 reqDevices.addAll(devAds.keySet());
1417 reqPorts.addAll(portAds.keySet());
1418
1419 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1420 log.trace("Nothing to request to remote peer {}", sender);
1421 return;
1422 }
1423
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001424 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001425
1426 // 2-way Anti-Entropy for now
1427 try {
1428 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1429 } catch (IOException e) {
1430 log.error("Failed to send response advertisement to " + sender, e);
1431 }
1432
1433// Sketch of 3-way Anti-Entropy
1434// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1435// ClusterMessage message = new ClusterMessage(
1436// clusterService.getLocalNode().id(),
1437// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1438// SERIALIZER.encode(request));
1439//
1440// try {
1441// clusterCommunicator.unicast(message, advertisement.sender());
1442// } catch (IOException e) {
1443// log.error("Failed to send advertisement reply to "
1444// + advertisement.sender(), e);
1445// }
Madan Jampani47c93732014-10-06 20:46:08 -07001446 }
1447
Madan Jampani255a58b2014-10-09 12:08:20 -07001448 private void notifyDelegateIfNotNull(DeviceEvent event) {
1449 if (event != null) {
1450 notifyDelegate(event);
1451 }
1452 }
1453
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001454 private final class SendAdvertisementTask implements Runnable {
1455
1456 @Override
1457 public void run() {
1458 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001459 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001460 return;
1461 }
1462
1463 try {
1464 final NodeId self = clusterService.getLocalNode().id();
1465 Set<ControllerNode> nodes = clusterService.getNodes();
1466
1467 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1468 .transform(toNodeId())
1469 .toList();
1470
1471 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001472 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001473 return;
1474 }
1475
1476 NodeId peer;
1477 do {
1478 int idx = RandomUtils.nextInt(0, nodeIds.size());
1479 peer = nodeIds.get(idx);
1480 } while (peer.equals(self));
1481
1482 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1483
1484 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001485 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001486 return;
1487 }
1488
1489 try {
1490 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1491 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001492 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001493 return;
1494 }
1495 } catch (Exception e) {
1496 // catch all Exception to avoid Scheduled task being suppressed.
1497 log.error("Exception thrown while sending advertisement", e);
1498 }
1499 }
1500 }
1501
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001502 private final class InternalDeviceEventListener
1503 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001504 @Override
1505 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001506 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001507 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001508
Madan Jampani47c93732014-10-06 20:46:08 -07001509 ProviderId providerId = event.providerId();
1510 DeviceId deviceId = event.deviceId();
1511 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001512
Madan Jampani2af244a2015-02-22 13:12:01 -08001513 try {
1514 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1515 } catch (Exception e) {
1516 log.warn("Exception thrown handling device update", e);
1517 }
Madan Jampani47c93732014-10-06 20:46:08 -07001518 }
1519 }
1520
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001521 private final class InternalDeviceOfflineEventListener
1522 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001523 @Override
1524 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001525 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001526 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001527
1528 DeviceId deviceId = event.deviceId();
1529 Timestamp timestamp = event.timestamp();
1530
Madan Jampani2af244a2015-02-22 13:12:01 -08001531 try {
1532 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1533 } catch (Exception e) {
1534 log.warn("Exception thrown handling device offline", e);
1535 }
Madan Jampani25322532014-10-08 11:20:38 -07001536 }
1537 }
1538
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001539 private final class InternalRemoveRequestListener
1540 implements ClusterMessageHandler {
1541 @Override
1542 public void handle(ClusterMessage message) {
1543 log.debug("Received device remove request from peer: {}", message.sender());
1544 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001545
Madan Jampani2af244a2015-02-22 13:12:01 -08001546 try {
1547 removeDevice(did);
1548 } catch (Exception e) {
1549 log.warn("Exception thrown handling device remove", e);
1550 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001551 }
1552 }
1553
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001554 private final class InternalDeviceRemovedEventListener
1555 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001556 @Override
1557 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001558 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001559 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001560
1561 DeviceId deviceId = event.deviceId();
1562 Timestamp timestamp = event.timestamp();
1563
Madan Jampani2af244a2015-02-22 13:12:01 -08001564 try {
1565 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1566 } catch (Exception e) {
1567 log.warn("Exception thrown handling device removed", e);
1568 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001569 }
1570 }
1571
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001572 private final class InternalPortEventListener
1573 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001574 @Override
1575 public void handle(ClusterMessage message) {
1576
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001577 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001578 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001579
1580 ProviderId providerId = event.providerId();
1581 DeviceId deviceId = event.deviceId();
1582 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1583
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001584 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001585 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001586 // Note: dropped information will be recovered by anti-entropy
1587 return;
1588 }
1589
Madan Jampani2af244a2015-02-22 13:12:01 -08001590 try {
1591 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1592 } catch (Exception e) {
1593 log.warn("Exception thrown handling port update", e);
1594 }
Madan Jampani47c93732014-10-06 20:46:08 -07001595 }
1596 }
1597
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001598 private final class InternalPortStatusEventListener
1599 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001600 @Override
1601 public void handle(ClusterMessage message) {
1602
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001603 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001604 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001605
1606 ProviderId providerId = event.providerId();
1607 DeviceId deviceId = event.deviceId();
1608 Timestamped<PortDescription> portDescription = event.portDescription();
1609
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001610 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001611 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001612 // Note: dropped information will be recovered by anti-entropy
1613 return;
1614 }
1615
Madan Jampani2af244a2015-02-22 13:12:01 -08001616 try {
1617 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1618 } catch (Exception e) {
1619 log.warn("Exception thrown handling port update", e);
1620 }
Madan Jampani47c93732014-10-06 20:46:08 -07001621 }
1622 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001623
1624 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001625 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001626 @Override
1627 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001628 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001629 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001630 try {
1631 handleAdvertisement(advertisement);
1632 } catch (Exception e) {
1633 log.warn("Exception thrown handling Device advertisements.", e);
1634 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001635 }
1636 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001637
1638 private final class DeviceInjectedEventListener
1639 implements ClusterMessageHandler {
1640 @Override
1641 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001642 log.debug("Received injected device event from peer: {}", message.sender());
1643 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1644
1645 ProviderId providerId = event.providerId();
1646 DeviceId deviceId = event.deviceId();
1647 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001648 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1649 // workaround for ONOS-1208
1650 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1651 return;
1652 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001653
Madan Jampani2af244a2015-02-22 13:12:01 -08001654 try {
1655 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1656 } catch (Exception e) {
1657 log.warn("Exception thrown handling device injected event.", e);
1658 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001659 }
1660 }
1661
1662 private final class PortInjectedEventListener
1663 implements ClusterMessageHandler {
1664 @Override
1665 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001666 log.debug("Received injected port event from peer: {}", message.sender());
1667 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1668
1669 ProviderId providerId = event.providerId();
1670 DeviceId deviceId = event.deviceId();
1671 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001672 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1673 // workaround for ONOS-1208
1674 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1675 return;
1676 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001677
Madan Jampani2af244a2015-02-22 13:12:01 -08001678 try {
1679 updatePorts(providerId, deviceId, portDescriptions);
1680 } catch (Exception e) {
1681 log.warn("Exception thrown handling port injected event.", e);
1682 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001683 }
1684 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001685
1686 private class InternalPortStatsListener
1687 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1688 @Override
1689 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1690 if (event.type() == PUT) {
1691 Device device = devices.get(event.key());
1692 if (device != null) {
1693 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1694 }
1695 }
1696 }
1697 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001698}