blob: a10b79d28857ae6e50e708e5fdb746953748271b [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 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;
99import java.util.concurrent.Executors;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700100import java.util.concurrent.ScheduledExecutorService;
101import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700102
103import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700104import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700105import static com.google.common.base.Verify.verify;
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() {
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800203 executor = Executors.newCachedThreadPool(groupedThreads("onos/device", "fg-%d"));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800204
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800205 backgroundExecutor =
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800206 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d")));
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) {
1088 switch (description.type()) {
1089 case OMS:
1090 OmsPortDescription omsDesc = (OmsPortDescription) description;
1091 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1092 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1093 case OCH:
1094 OchPortDescription ochDesc = (OchPortDescription) description;
1095 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1096 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1097 case ODUCLT:
1098 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1099 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +02001100 case OTU:
1101 OtuPortDescription otuDesc = (OtuPortDescription) description;
1102 return new OtuPort(device, number, isEnabled, otuDesc.signalType(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001103 default:
1104 return new DefaultPort(device, number, isEnabled, description.type(),
1105 description.portSpeed(), annotations);
1106 }
1107 }
1108
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001109 /**
1110 * Returns a Port, merging description given from multiple Providers.
1111 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001112 * @param device device the port is on
1113 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001114 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001115 * @return Port instance
1116 */
1117 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001118 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001119
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001120 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001121 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001122 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001123 boolean isEnabled = false;
1124 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001125 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001126 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1127 if (portDesc != null) {
1128 isEnabled = portDesc.value().isEnabled();
1129 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001130 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001131 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001132 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001133 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001134 if (e.getKey().equals(primary)) {
1135 continue;
1136 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001137 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001138 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001139 // Currently assuming there will never be a key conflict between
1140 // providers
1141
1142 // annotation merging. not so efficient, should revisit later
1143 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1144 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001145 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1146 continue;
1147 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001148 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001149 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001150 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001151 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001152 }
1153 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001154 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001155 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001156 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001157 PortDescription current = portDesc.value();
1158 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001159 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001160 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001161 }
1162
1163 /**
1164 * @return primary ProviderID, or randomly chosen one if none exists
1165 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001166 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001167 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001168 ProviderId fallBackPrimary = null;
1169 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1170 if (!e.getKey().isAncillary()) {
1171 return e.getKey();
1172 } else if (fallBackPrimary == null) {
1173 // pick randomly as a fallback in case there is no primary
1174 fallBackPrimary = e.getKey();
1175 }
1176 }
1177 return fallBackPrimary;
1178 }
1179
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001180 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001181 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001182 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001183 return providerDescs.get(pid);
1184 }
1185
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001186 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001187 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001188 }
1189
Jonathan Hart7d656f42015-01-27 14:07:23 -08001190 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001191 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001192 }
Madan Jampani47c93732014-10-06 20:46:08 -07001193
Jonathan Hart7d656f42015-01-27 14:07:23 -08001194 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001195 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001196 }
1197
Jonathan Hart7d656f42015-01-27 14:07:23 -08001198 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001199 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001200 }
1201
Jonathan Hart7d656f42015-01-27 14:07:23 -08001202 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001203 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001204 }
1205
Jonathan Hart7d656f42015-01-27 14:07:23 -08001206 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001207 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001208 }
1209
Jonathan Hart7d656f42015-01-27 14:07:23 -08001210 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001211 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1212 }
1213
1214 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1215 try {
1216 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1217 } catch (IOException e) {
1218 log.error("Failed to send" + event + " to " + recipient, e);
1219 }
1220 }
1221
1222 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1223 try {
1224 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1225 } catch (IOException e) {
1226 log.error("Failed to send" + event + " to " + recipient, e);
1227 }
1228 }
1229
1230 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1231 try {
1232 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1233 } catch (IOException e) {
1234 log.error("Failed to send" + event + " to " + recipient, e);
1235 }
1236 }
1237
1238 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1239 try {
1240 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1241 } catch (IOException e) {
1242 log.error("Failed to send" + event + " to " + recipient, e);
1243 }
1244 }
1245
1246 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1247 try {
1248 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1249 } catch (IOException e) {
1250 log.error("Failed to send" + event + " to " + recipient, e);
1251 }
1252 }
1253
1254 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1255 final NodeId self = clusterService.getLocalNode().id();
1256
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001257 final int numDevices = deviceDescs.size();
1258 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1259 final int portsPerDevice = 8; // random factor to minimize reallocation
1260 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1261 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001262
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001263 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001264
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001265 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001266 synchronized (devDescs) {
1267
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001268 // send device offline timestamp
1269 Timestamp lOffline = this.offline.get(deviceId);
1270 if (lOffline != null) {
1271 adOffline.put(deviceId, lOffline);
1272 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001273
1274 for (Entry<ProviderId, DeviceDescriptions>
1275 prov : devDescs.entrySet()) {
1276
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001277 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001278 final ProviderId provId = prov.getKey();
1279 final DeviceDescriptions descs = prov.getValue();
1280
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001281 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001282 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001283
1284 for (Entry<PortNumber, Timestamped<PortDescription>>
1285 portDesc : descs.getPortDescs().entrySet()) {
1286
1287 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001288 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001289 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001290 }
1291 }
1292 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001293 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001294
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001295 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001296 }
1297
1298 /**
1299 * Responds to anti-entropy advertisement message.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001300 * <p/>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001301 * Notify sender about out-dated information using regular replication message.
1302 * Send back advertisement to sender if not in sync.
1303 *
1304 * @param advertisement to respond to
1305 */
1306 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1307
1308 final NodeId sender = advertisement.sender();
1309
1310 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1311 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1312 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1313
1314 // Fragments to request
1315 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1316 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1317
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001318 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001319 final DeviceId deviceId = de.getKey();
1320 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1321
1322 synchronized (lDevice) {
1323 // latestTimestamp across provider
1324 // Note: can be null initially
1325 Timestamp localLatest = offline.get(deviceId);
1326
1327 // handle device Ads
1328 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1329 final ProviderId provId = prov.getKey();
1330 final DeviceDescriptions lDeviceDescs = prov.getValue();
1331
1332 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1333
1334
1335 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1336 Timestamp advDevTimestamp = devAds.get(devFragId);
1337
Jonathan Hart403ea932015-02-20 16:23:00 -08001338 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1339 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001340 // remote does not have it or outdated, suggest
1341 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1342 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1343 // local is outdated, request
1344 reqDevices.add(devFragId);
1345 }
1346
1347 // handle port Ads
1348 for (Entry<PortNumber, Timestamped<PortDescription>>
1349 pe : lDeviceDescs.getPortDescs().entrySet()) {
1350
1351 final PortNumber num = pe.getKey();
1352 final Timestamped<PortDescription> lPort = pe.getValue();
1353
1354 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1355
1356 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001357 if (advPortTimestamp == null || lPort.isNewerThan(
1358 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001359 // remote does not have it or outdated, suggest
1360 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1361 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1362 // local is outdated, request
1363 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1364 reqPorts.add(portFragId);
1365 }
1366
1367 // remove port Ad already processed
1368 portAds.remove(portFragId);
1369 } // end local port loop
1370
1371 // remove device Ad already processed
1372 devAds.remove(devFragId);
1373
1374 // find latest and update
1375 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1376 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001377 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001378 localLatest = providerLatest;
1379 }
1380 } // end local provider loop
1381
1382 // checking if remote timestamp is more recent.
1383 Timestamp rOffline = offlineAds.get(deviceId);
1384 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001385 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001386 // remote offline timestamp suggests that the
1387 // device is off-line
1388 markOfflineInternal(deviceId, rOffline);
1389 }
1390
1391 Timestamp lOffline = offline.get(deviceId);
1392 if (lOffline != null && rOffline == null) {
1393 // locally offline, but remote is online, suggest offline
1394 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1395 }
1396
1397 // remove device offline Ad already processed
1398 offlineAds.remove(deviceId);
1399 } // end local device loop
1400 } // device lock
1401
1402 // If there is any Ads left, request them
1403 log.trace("Ads left {}, {}", devAds, portAds);
1404 reqDevices.addAll(devAds.keySet());
1405 reqPorts.addAll(portAds.keySet());
1406
1407 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1408 log.trace("Nothing to request to remote peer {}", sender);
1409 return;
1410 }
1411
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001412 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001413
1414 // 2-way Anti-Entropy for now
1415 try {
1416 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1417 } catch (IOException e) {
1418 log.error("Failed to send response advertisement to " + sender, e);
1419 }
1420
1421// Sketch of 3-way Anti-Entropy
1422// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1423// ClusterMessage message = new ClusterMessage(
1424// clusterService.getLocalNode().id(),
1425// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1426// SERIALIZER.encode(request));
1427//
1428// try {
1429// clusterCommunicator.unicast(message, advertisement.sender());
1430// } catch (IOException e) {
1431// log.error("Failed to send advertisement reply to "
1432// + advertisement.sender(), e);
1433// }
Madan Jampani47c93732014-10-06 20:46:08 -07001434 }
1435
Madan Jampani255a58b2014-10-09 12:08:20 -07001436 private void notifyDelegateIfNotNull(DeviceEvent event) {
1437 if (event != null) {
1438 notifyDelegate(event);
1439 }
1440 }
1441
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001442 private final class SendAdvertisementTask implements Runnable {
1443
1444 @Override
1445 public void run() {
1446 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001447 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001448 return;
1449 }
1450
1451 try {
1452 final NodeId self = clusterService.getLocalNode().id();
1453 Set<ControllerNode> nodes = clusterService.getNodes();
1454
1455 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1456 .transform(toNodeId())
1457 .toList();
1458
1459 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001460 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001461 return;
1462 }
1463
1464 NodeId peer;
1465 do {
1466 int idx = RandomUtils.nextInt(0, nodeIds.size());
1467 peer = nodeIds.get(idx);
1468 } while (peer.equals(self));
1469
1470 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1471
1472 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001473 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001474 return;
1475 }
1476
1477 try {
1478 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1479 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001480 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001481 return;
1482 }
1483 } catch (Exception e) {
1484 // catch all Exception to avoid Scheduled task being suppressed.
1485 log.error("Exception thrown while sending advertisement", e);
1486 }
1487 }
1488 }
1489
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001490 private final class InternalDeviceEventListener
1491 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001492 @Override
1493 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001494 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001495 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001496
Madan Jampani47c93732014-10-06 20:46:08 -07001497 ProviderId providerId = event.providerId();
1498 DeviceId deviceId = event.deviceId();
1499 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001500
Madan Jampani2af244a2015-02-22 13:12:01 -08001501 try {
1502 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1503 } catch (Exception e) {
1504 log.warn("Exception thrown handling device update", e);
1505 }
Madan Jampani47c93732014-10-06 20:46:08 -07001506 }
1507 }
1508
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001509 private final class InternalDeviceOfflineEventListener
1510 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001511 @Override
1512 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001513 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001514 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001515
1516 DeviceId deviceId = event.deviceId();
1517 Timestamp timestamp = event.timestamp();
1518
Madan Jampani2af244a2015-02-22 13:12:01 -08001519 try {
1520 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1521 } catch (Exception e) {
1522 log.warn("Exception thrown handling device offline", e);
1523 }
Madan Jampani25322532014-10-08 11:20:38 -07001524 }
1525 }
1526
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001527 private final class InternalRemoveRequestListener
1528 implements ClusterMessageHandler {
1529 @Override
1530 public void handle(ClusterMessage message) {
1531 log.debug("Received device remove request from peer: {}", message.sender());
1532 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001533
Madan Jampani2af244a2015-02-22 13:12:01 -08001534 try {
1535 removeDevice(did);
1536 } catch (Exception e) {
1537 log.warn("Exception thrown handling device remove", e);
1538 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001539 }
1540 }
1541
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001542 private final class InternalDeviceRemovedEventListener
1543 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001544 @Override
1545 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001546 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001547 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001548
1549 DeviceId deviceId = event.deviceId();
1550 Timestamp timestamp = event.timestamp();
1551
Madan Jampani2af244a2015-02-22 13:12:01 -08001552 try {
1553 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1554 } catch (Exception e) {
1555 log.warn("Exception thrown handling device removed", e);
1556 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001557 }
1558 }
1559
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001560 private final class InternalPortEventListener
1561 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001562 @Override
1563 public void handle(ClusterMessage message) {
1564
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001565 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001566 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001567
1568 ProviderId providerId = event.providerId();
1569 DeviceId deviceId = event.deviceId();
1570 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1571
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001572 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001573 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001574 // Note: dropped information will be recovered by anti-entropy
1575 return;
1576 }
1577
Madan Jampani2af244a2015-02-22 13:12:01 -08001578 try {
1579 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1580 } catch (Exception e) {
1581 log.warn("Exception thrown handling port update", e);
1582 }
Madan Jampani47c93732014-10-06 20:46:08 -07001583 }
1584 }
1585
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001586 private final class InternalPortStatusEventListener
1587 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001588 @Override
1589 public void handle(ClusterMessage message) {
1590
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001591 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001592 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001593
1594 ProviderId providerId = event.providerId();
1595 DeviceId deviceId = event.deviceId();
1596 Timestamped<PortDescription> portDescription = event.portDescription();
1597
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001598 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001599 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001600 // Note: dropped information will be recovered by anti-entropy
1601 return;
1602 }
1603
Madan Jampani2af244a2015-02-22 13:12:01 -08001604 try {
1605 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1606 } catch (Exception e) {
1607 log.warn("Exception thrown handling port update", e);
1608 }
Madan Jampani47c93732014-10-06 20:46:08 -07001609 }
1610 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001611
1612 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001613 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001614 @Override
1615 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001616 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001617 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001618 try {
1619 handleAdvertisement(advertisement);
1620 } catch (Exception e) {
1621 log.warn("Exception thrown handling Device advertisements.", e);
1622 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001623 }
1624 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001625
1626 private final class DeviceInjectedEventListener
1627 implements ClusterMessageHandler {
1628 @Override
1629 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001630 log.debug("Received injected device event from peer: {}", message.sender());
1631 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1632
1633 ProviderId providerId = event.providerId();
1634 DeviceId deviceId = event.deviceId();
1635 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001636 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1637 // workaround for ONOS-1208
1638 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1639 return;
1640 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001641
Madan Jampani2af244a2015-02-22 13:12:01 -08001642 try {
1643 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1644 } catch (Exception e) {
1645 log.warn("Exception thrown handling device injected event.", e);
1646 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001647 }
1648 }
1649
1650 private final class PortInjectedEventListener
1651 implements ClusterMessageHandler {
1652 @Override
1653 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001654 log.debug("Received injected port event from peer: {}", message.sender());
1655 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1656
1657 ProviderId providerId = event.providerId();
1658 DeviceId deviceId = event.deviceId();
1659 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001660 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1661 // workaround for ONOS-1208
1662 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1663 return;
1664 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001665
Madan Jampani2af244a2015-02-22 13:12:01 -08001666 try {
1667 updatePorts(providerId, deviceId, portDescriptions);
1668 } catch (Exception e) {
1669 log.warn("Exception thrown handling port injected event.", e);
1670 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001671 }
1672 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001673
1674 private class InternalPortStatsListener
1675 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1676 @Override
1677 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1678 if (event.type() == PUT) {
1679 Device device = devices.get(event.key());
1680 if (device != null) {
1681 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1682 }
1683 }
1684 }
1685 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001686}