blob: ea25e8c98145897db7d7bc6619b80542705cf3bf [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:
HIGUCHI Yuta4c0ef6b2016-05-02 19:45:41 -07001110 if (description instanceof OduCltPortDescription) {
1111 // remove if-block once deprecation is complete
1112 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1113 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1114 }
1115 // same as default
1116 return new DefaultPort(device, number, isEnabled, description.type(),
1117 description.portSpeed(), annotations);
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +02001118 case OTU:
1119 OtuPortDescription otuDesc = (OtuPortDescription) description;
1120 return new OtuPort(device, number, isEnabled, otuDesc.signalType(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001121 default:
1122 return new DefaultPort(device, number, isEnabled, description.type(),
1123 description.portSpeed(), annotations);
1124 }
1125 }
1126
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001127 /**
1128 * Returns a Port, merging description given from multiple Providers.
1129 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001130 * @param device device the port is on
1131 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001132 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001133 * @return Port instance
1134 */
1135 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001136 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001137
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001138 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001139 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001140 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001141 boolean isEnabled = false;
1142 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001143 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001144 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1145 if (portDesc != null) {
1146 isEnabled = portDesc.value().isEnabled();
1147 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001148 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001149 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001150 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001151 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001152 if (e.getKey().equals(primary)) {
1153 continue;
1154 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001155 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001156 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001157 // Currently assuming there will never be a key conflict between
1158 // providers
1159
1160 // annotation merging. not so efficient, should revisit later
1161 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1162 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001163 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1164 continue;
1165 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001166 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001167 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001168 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001169 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001170 }
1171 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001172 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001173 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001174 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001175 PortDescription current = portDesc.value();
1176 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001177 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001178 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001179 }
1180
1181 /**
1182 * @return primary ProviderID, or randomly chosen one if none exists
1183 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001184 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001185 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001186 ProviderId fallBackPrimary = null;
1187 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1188 if (!e.getKey().isAncillary()) {
1189 return e.getKey();
1190 } else if (fallBackPrimary == null) {
1191 // pick randomly as a fallback in case there is no primary
1192 fallBackPrimary = e.getKey();
1193 }
1194 }
1195 return fallBackPrimary;
1196 }
1197
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001198 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001199 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001200 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001201 return providerDescs.get(pid);
1202 }
1203
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001204 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001205 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001206 }
1207
Jonathan Hart7d656f42015-01-27 14:07:23 -08001208 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001209 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001210 }
Madan Jampani47c93732014-10-06 20:46:08 -07001211
Jonathan Hart7d656f42015-01-27 14:07:23 -08001212 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001213 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001214 }
1215
Jonathan Hart7d656f42015-01-27 14:07:23 -08001216 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001217 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001218 }
1219
Jonathan Hart7d656f42015-01-27 14:07:23 -08001220 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001221 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001222 }
1223
Jonathan Hart7d656f42015-01-27 14:07:23 -08001224 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001225 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001226 }
1227
Jonathan Hart7d656f42015-01-27 14:07:23 -08001228 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001229 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1230 }
1231
1232 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1233 try {
1234 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1235 } catch (IOException e) {
1236 log.error("Failed to send" + event + " to " + recipient, e);
1237 }
1238 }
1239
1240 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1241 try {
1242 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1243 } catch (IOException e) {
1244 log.error("Failed to send" + event + " to " + recipient, e);
1245 }
1246 }
1247
1248 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1249 try {
1250 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1251 } catch (IOException e) {
1252 log.error("Failed to send" + event + " to " + recipient, e);
1253 }
1254 }
1255
1256 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1257 try {
1258 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1259 } catch (IOException e) {
1260 log.error("Failed to send" + event + " to " + recipient, e);
1261 }
1262 }
1263
1264 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1265 try {
1266 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1267 } catch (IOException e) {
1268 log.error("Failed to send" + event + " to " + recipient, e);
1269 }
1270 }
1271
1272 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1273 final NodeId self = clusterService.getLocalNode().id();
1274
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001275 final int numDevices = deviceDescs.size();
1276 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1277 final int portsPerDevice = 8; // random factor to minimize reallocation
1278 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1279 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001280
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001281 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001282
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001283 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001284 synchronized (devDescs) {
1285
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001286 // send device offline timestamp
1287 Timestamp lOffline = this.offline.get(deviceId);
1288 if (lOffline != null) {
1289 adOffline.put(deviceId, lOffline);
1290 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001291
1292 for (Entry<ProviderId, DeviceDescriptions>
1293 prov : devDescs.entrySet()) {
1294
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001295 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001296 final ProviderId provId = prov.getKey();
1297 final DeviceDescriptions descs = prov.getValue();
1298
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001299 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001300 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001301
1302 for (Entry<PortNumber, Timestamped<PortDescription>>
1303 portDesc : descs.getPortDescs().entrySet()) {
1304
1305 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001306 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001307 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001308 }
1309 }
1310 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001311 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001312
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001313 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001314 }
1315
1316 /**
1317 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001318 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001319 * Notify sender about out-dated information using regular replication message.
1320 * Send back advertisement to sender if not in sync.
1321 *
1322 * @param advertisement to respond to
1323 */
1324 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1325
1326 final NodeId sender = advertisement.sender();
1327
1328 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1329 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1330 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1331
1332 // Fragments to request
1333 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1334 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1335
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001336 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001337 final DeviceId deviceId = de.getKey();
1338 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1339
1340 synchronized (lDevice) {
1341 // latestTimestamp across provider
1342 // Note: can be null initially
1343 Timestamp localLatest = offline.get(deviceId);
1344
1345 // handle device Ads
1346 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1347 final ProviderId provId = prov.getKey();
1348 final DeviceDescriptions lDeviceDescs = prov.getValue();
1349
1350 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1351
1352
1353 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1354 Timestamp advDevTimestamp = devAds.get(devFragId);
1355
Jonathan Hart403ea932015-02-20 16:23:00 -08001356 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1357 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001358 // remote does not have it or outdated, suggest
1359 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1360 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1361 // local is outdated, request
1362 reqDevices.add(devFragId);
1363 }
1364
1365 // handle port Ads
1366 for (Entry<PortNumber, Timestamped<PortDescription>>
1367 pe : lDeviceDescs.getPortDescs().entrySet()) {
1368
1369 final PortNumber num = pe.getKey();
1370 final Timestamped<PortDescription> lPort = pe.getValue();
1371
1372 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1373
1374 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001375 if (advPortTimestamp == null || lPort.isNewerThan(
1376 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001377 // remote does not have it or outdated, suggest
1378 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1379 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1380 // local is outdated, request
1381 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1382 reqPorts.add(portFragId);
1383 }
1384
1385 // remove port Ad already processed
1386 portAds.remove(portFragId);
1387 } // end local port loop
1388
1389 // remove device Ad already processed
1390 devAds.remove(devFragId);
1391
1392 // find latest and update
1393 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1394 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001395 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001396 localLatest = providerLatest;
1397 }
1398 } // end local provider loop
1399
1400 // checking if remote timestamp is more recent.
1401 Timestamp rOffline = offlineAds.get(deviceId);
1402 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001403 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001404 // remote offline timestamp suggests that the
1405 // device is off-line
1406 markOfflineInternal(deviceId, rOffline);
1407 }
1408
1409 Timestamp lOffline = offline.get(deviceId);
1410 if (lOffline != null && rOffline == null) {
1411 // locally offline, but remote is online, suggest offline
1412 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1413 }
1414
1415 // remove device offline Ad already processed
1416 offlineAds.remove(deviceId);
1417 } // end local device loop
1418 } // device lock
1419
1420 // If there is any Ads left, request them
1421 log.trace("Ads left {}, {}", devAds, portAds);
1422 reqDevices.addAll(devAds.keySet());
1423 reqPorts.addAll(portAds.keySet());
1424
1425 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1426 log.trace("Nothing to request to remote peer {}", sender);
1427 return;
1428 }
1429
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001430 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001431
1432 // 2-way Anti-Entropy for now
1433 try {
1434 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1435 } catch (IOException e) {
1436 log.error("Failed to send response advertisement to " + sender, e);
1437 }
1438
1439// Sketch of 3-way Anti-Entropy
1440// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1441// ClusterMessage message = new ClusterMessage(
1442// clusterService.getLocalNode().id(),
1443// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1444// SERIALIZER.encode(request));
1445//
1446// try {
1447// clusterCommunicator.unicast(message, advertisement.sender());
1448// } catch (IOException e) {
1449// log.error("Failed to send advertisement reply to "
1450// + advertisement.sender(), e);
1451// }
Madan Jampani47c93732014-10-06 20:46:08 -07001452 }
1453
Madan Jampani255a58b2014-10-09 12:08:20 -07001454 private void notifyDelegateIfNotNull(DeviceEvent event) {
1455 if (event != null) {
1456 notifyDelegate(event);
1457 }
1458 }
1459
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001460 private final class SendAdvertisementTask implements Runnable {
1461
1462 @Override
1463 public void run() {
1464 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001465 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001466 return;
1467 }
1468
1469 try {
1470 final NodeId self = clusterService.getLocalNode().id();
1471 Set<ControllerNode> nodes = clusterService.getNodes();
1472
1473 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1474 .transform(toNodeId())
1475 .toList();
1476
1477 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001478 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001479 return;
1480 }
1481
1482 NodeId peer;
1483 do {
1484 int idx = RandomUtils.nextInt(0, nodeIds.size());
1485 peer = nodeIds.get(idx);
1486 } while (peer.equals(self));
1487
1488 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1489
1490 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001491 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001492 return;
1493 }
1494
1495 try {
1496 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1497 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001498 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001499 return;
1500 }
1501 } catch (Exception e) {
1502 // catch all Exception to avoid Scheduled task being suppressed.
1503 log.error("Exception thrown while sending advertisement", e);
1504 }
1505 }
1506 }
1507
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001508 private final class InternalDeviceEventListener
1509 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001510 @Override
1511 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001512 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001513 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001514
Madan Jampani47c93732014-10-06 20:46:08 -07001515 ProviderId providerId = event.providerId();
1516 DeviceId deviceId = event.deviceId();
1517 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001518
Madan Jampani2af244a2015-02-22 13:12:01 -08001519 try {
1520 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1521 } catch (Exception e) {
1522 log.warn("Exception thrown handling device update", e);
1523 }
Madan Jampani47c93732014-10-06 20:46:08 -07001524 }
1525 }
1526
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001527 private final class InternalDeviceOfflineEventListener
1528 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001529 @Override
1530 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001531 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001532 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001533
1534 DeviceId deviceId = event.deviceId();
1535 Timestamp timestamp = event.timestamp();
1536
Madan Jampani2af244a2015-02-22 13:12:01 -08001537 try {
1538 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1539 } catch (Exception e) {
1540 log.warn("Exception thrown handling device offline", e);
1541 }
Madan Jampani25322532014-10-08 11:20:38 -07001542 }
1543 }
1544
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001545 private final class InternalRemoveRequestListener
1546 implements ClusterMessageHandler {
1547 @Override
1548 public void handle(ClusterMessage message) {
1549 log.debug("Received device remove request from peer: {}", message.sender());
1550 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001551
Madan Jampani2af244a2015-02-22 13:12:01 -08001552 try {
1553 removeDevice(did);
1554 } catch (Exception e) {
1555 log.warn("Exception thrown handling device remove", e);
1556 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001557 }
1558 }
1559
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001560 private final class InternalDeviceRemovedEventListener
1561 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001562 @Override
1563 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001564 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001565 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001566
1567 DeviceId deviceId = event.deviceId();
1568 Timestamp timestamp = event.timestamp();
1569
Madan Jampani2af244a2015-02-22 13:12:01 -08001570 try {
1571 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1572 } catch (Exception e) {
1573 log.warn("Exception thrown handling device removed", e);
1574 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001575 }
1576 }
1577
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001578 private final class InternalPortEventListener
1579 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001580 @Override
1581 public void handle(ClusterMessage message) {
1582
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001583 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001584 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001585
1586 ProviderId providerId = event.providerId();
1587 DeviceId deviceId = event.deviceId();
1588 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1589
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001590 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001591 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001592 // Note: dropped information will be recovered by anti-entropy
1593 return;
1594 }
1595
Madan Jampani2af244a2015-02-22 13:12:01 -08001596 try {
1597 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1598 } catch (Exception e) {
1599 log.warn("Exception thrown handling port update", e);
1600 }
Madan Jampani47c93732014-10-06 20:46:08 -07001601 }
1602 }
1603
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001604 private final class InternalPortStatusEventListener
1605 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001606 @Override
1607 public void handle(ClusterMessage message) {
1608
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001609 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001610 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001611
1612 ProviderId providerId = event.providerId();
1613 DeviceId deviceId = event.deviceId();
1614 Timestamped<PortDescription> portDescription = event.portDescription();
1615
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001616 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001617 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001618 // Note: dropped information will be recovered by anti-entropy
1619 return;
1620 }
1621
Madan Jampani2af244a2015-02-22 13:12:01 -08001622 try {
1623 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1624 } catch (Exception e) {
1625 log.warn("Exception thrown handling port update", e);
1626 }
Madan Jampani47c93732014-10-06 20:46:08 -07001627 }
1628 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001629
1630 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001631 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001632 @Override
1633 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001634 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001635 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001636 try {
1637 handleAdvertisement(advertisement);
1638 } catch (Exception e) {
1639 log.warn("Exception thrown handling Device advertisements.", e);
1640 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001641 }
1642 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001643
1644 private final class DeviceInjectedEventListener
1645 implements ClusterMessageHandler {
1646 @Override
1647 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001648 log.debug("Received injected device event from peer: {}", message.sender());
1649 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1650
1651 ProviderId providerId = event.providerId();
1652 DeviceId deviceId = event.deviceId();
1653 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001654 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1655 // workaround for ONOS-1208
1656 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1657 return;
1658 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001659
Madan Jampani2af244a2015-02-22 13:12:01 -08001660 try {
1661 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1662 } catch (Exception e) {
1663 log.warn("Exception thrown handling device injected event.", e);
1664 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001665 }
1666 }
1667
1668 private final class PortInjectedEventListener
1669 implements ClusterMessageHandler {
1670 @Override
1671 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001672 log.debug("Received injected port event from peer: {}", message.sender());
1673 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1674
1675 ProviderId providerId = event.providerId();
1676 DeviceId deviceId = event.deviceId();
1677 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001678 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1679 // workaround for ONOS-1208
1680 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1681 return;
1682 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001683
Madan Jampani2af244a2015-02-22 13:12:01 -08001684 try {
1685 updatePorts(providerId, deviceId, portDescriptions);
1686 } catch (Exception e) {
1687 log.warn("Exception thrown handling port injected event.", e);
1688 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001689 }
1690 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001691
1692 private class InternalPortStatsListener
1693 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1694 @Override
1695 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1696 if (event.type() == PUT) {
1697 Device device = devices.get(event.key());
1698 if (device != null) {
1699 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1700 }
1701 }
1702 }
1703 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001704}