blob: 03e28f193544af5b9fbe42fa50118321e60c3a06 [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;
Brian O'Connorabafb502014-12-02 22:26:20 -080051import org.onosproject.net.Port;
52import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070053import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080054import org.onosproject.net.device.DeviceClockService;
55import org.onosproject.net.device.DeviceDescription;
56import org.onosproject.net.device.DeviceEvent;
57import org.onosproject.net.device.DeviceStore;
58import org.onosproject.net.device.DeviceStoreDelegate;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070059import org.onosproject.net.device.OchPortDescription;
60import org.onosproject.net.device.OduCltPortDescription;
61import org.onosproject.net.device.OmsPortDescription;
Brian O'Connorabafb502014-12-02 22:26:20 -080062import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070063import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080064import org.onosproject.net.provider.ProviderId;
65import org.onosproject.store.AbstractStore;
66import org.onosproject.store.Timestamp;
67import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
68import org.onosproject.store.cluster.messaging.ClusterMessage;
69import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
70import org.onosproject.store.cluster.messaging.MessageSubject;
71import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070072import org.onosproject.store.serializers.KryoNamespaces;
Brian O'Connorabafb502014-12-02 22:26:20 -080073import org.onosproject.store.serializers.KryoSerializer;
Brian O'Connor6de2e202015-05-21 14:30:41 -070074import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070075import org.onosproject.store.service.EventuallyConsistentMap;
76import org.onosproject.store.service.EventuallyConsistentMapEvent;
77import org.onosproject.store.service.EventuallyConsistentMapListener;
78import org.onosproject.store.service.MultiValuedTimestamp;
79import org.onosproject.store.service.StorageService;
80import org.onosproject.store.service.WallClockTimestamp;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070081import org.slf4j.Logger;
82
Madan Jampani47c93732014-10-06 20:46:08 -070083import java.io.IOException;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070084import java.util.ArrayList;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070085import java.util.Collection;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070086import java.util.Collections;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070087import java.util.HashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070088import java.util.HashSet;
89import java.util.Iterator;
90import java.util.List;
91import java.util.Map;
92import java.util.Map.Entry;
93import java.util.Objects;
94import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070095import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080096import java.util.concurrent.ExecutorService;
97import java.util.concurrent.Executors;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070098import java.util.concurrent.ScheduledExecutorService;
99import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700100
101import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700102import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700103import static com.google.common.base.Verify.verify;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800104import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
105import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800106import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800107import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800108import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
109import static org.onosproject.net.DefaultAnnotations.merge;
110import static org.onosproject.net.device.DeviceEvent.Type.*;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800111import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700112import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800113import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700114
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700115/**
116 * Manages inventory of infrastructure devices using gossip protocol to distribute
117 * information.
118 */
119@Component(immediate = true)
120@Service
121public class GossipDeviceStore
122 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
123 implements DeviceStore {
124
125 private final Logger log = getLogger(getClass());
126
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700127 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800128 // Timeout in milliseconds to process device or ports on remote master node
129 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700130
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700131 // innerMap is used to lock a Device, thus instance should never be replaced.
132 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700133 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700134 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700135
136 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700137 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
138 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700139
140 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200141 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700142 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
143 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700144
145 // to be updated under Device lock
146 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
147 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700148
149 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700150 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700151
152 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700153 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700154
Madan Jampani47c93732014-10-06 20:46:08 -0700155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700156 protected StorageService storageService;
157
158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700159 protected ClusterCommunicationService clusterCommunicator;
160
Madan Jampani53e44e62014-10-07 12:39:51 -0700161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
162 protected ClusterService clusterService;
163
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
165 protected MastershipService mastershipService;
166
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
168 protected MastershipTermService termService;
169
170
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700171 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700172 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700173 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700174 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800175 .register(DistributedStoreSerializers.STORE_COMMON)
176 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
177 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
178 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700179 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800180 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
181 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700182 .register(DeviceAntiEntropyAdvertisement.class)
183 .register(DeviceFragmentId.class)
184 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800185 .register(DeviceInjectedEvent.class)
186 .register(PortInjectedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800187 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700188 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700189 };
190
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800191 private ExecutorService executor;
192
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800193 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700194
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800195 // TODO make these anti-entropy parameters configurable
196 private long initialDelaySec = 5;
197 private long periodSec = 5;
198
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700199 @Activate
200 public void activate() {
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800201 executor = Executors.newCachedThreadPool(groupedThreads("onos/device", "fg-%d"));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800202
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800203 backgroundExecutor =
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800204 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700205
Madan Jampani2af244a2015-02-22 13:12:01 -0800206 clusterCommunicator.addSubscriber(
207 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
208 clusterCommunicator.addSubscriber(
209 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
210 new InternalDeviceOfflineEventListener(),
211 executor);
212 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700213 new InternalRemoveRequestListener(),
214 executor);
Madan Jampani2af244a2015-02-22 13:12:01 -0800215 clusterCommunicator.addSubscriber(
216 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
217 clusterCommunicator.addSubscriber(
218 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
219 clusterCommunicator.addSubscriber(
220 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
221 clusterCommunicator.addSubscriber(
222 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
223 new InternalDeviceAdvertisementListener(),
224 backgroundExecutor);
225 clusterCommunicator.addSubscriber(
226 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
227 clusterCommunicator.addSubscriber(
228 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
229
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700230 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800231 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700232 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700233
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700234 // Create a distributed map for port stats.
235 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
236 .register(KryoNamespaces.API)
237 .register(DefaultPortStatistics.class)
238 .register(DeviceId.class)
239 .register(MultiValuedTimestamp.class)
240 .register(WallClockTimestamp.class);
241
242 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
243 .withName("port-stats")
244 .withSerializer(deviceDataSerializer)
245 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700246 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700247 .withTombstonesDisabled()
248 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200249 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
250 eventuallyConsistentMapBuilder()
251 .withName("port-stats-delta")
252 .withSerializer(deviceDataSerializer)
253 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
254 .withTimestampProvider((k, v) -> new WallClockTimestamp())
255 .withTombstonesDisabled()
256 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700257 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700258 log.info("Started");
259 }
260
261 @Deactivate
262 public void deactivate() {
Madan Jampani632f16b2015-08-11 12:42:59 -0700263 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200264 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800265 executor.shutdownNow();
266
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800267 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700268 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800269 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700270 log.error("Timeout during executor shutdown");
271 }
272 } catch (InterruptedException e) {
273 log.error("Error during executor shutdown", e);
274 }
275
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700276 deviceDescs.clear();
277 devices.clear();
278 devicePorts.clear();
279 availableDevices.clear();
280 log.info("Stopped");
281 }
282
283 @Override
284 public int getDeviceCount() {
285 return devices.size();
286 }
287
288 @Override
289 public Iterable<Device> getDevices() {
290 return Collections.unmodifiableCollection(devices.values());
291 }
292
293 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800294 public Iterable<Device> getAvailableDevices() {
295 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700296 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800297 }
298
299 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700300 public Device getDevice(DeviceId deviceId) {
301 return devices.get(deviceId);
302 }
303
304 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700305 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700306 DeviceId deviceId,
307 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800308 NodeId localNode = clusterService.getLocalNode().id();
309 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
310
311 // Process device update only if we're the master,
312 // otherwise signal the actual master.
313 DeviceEvent deviceEvent = null;
314 if (localNode.equals(deviceNode)) {
315
316 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
317 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
318 final Timestamped<DeviceDescription> mergedDesc;
319 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
320
321 synchronized (device) {
322 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
323 mergedDesc = device.get(providerId).getDeviceDesc();
324 }
325
326 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700327 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700328 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800329 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
330 }
331
332 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800333 // Only forward for ConfigProvider
334 // Forwarding was added as a workaround for ONOS-490
335 if (!providerId.equals("cfg")) {
336 return null;
337 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800338 // FIXME Temporary hack for NPE (ONOS-1171).
339 // Proper fix is to implement forwarding to master on ConfigProvider
340 // redo ONOS-490
341 if (deviceNode == null) {
342 // silently ignore
343 return null;
344 }
345
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800346
347 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
348 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800349
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800350 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700351 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800352 /* error log:
353 log.warn("Failed to process injected device id: {} desc: {} " +
354 "(cluster messaging failed: {})",
355 deviceId, deviceDescription, e);
356 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700357 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800358
359 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700360 }
361
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700362 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700363 DeviceId deviceId,
364 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700365
366 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800367 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700368 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700369
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800370 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700371 // locking per device
372
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700373 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
374 log.debug("Ignoring outdated event: {}", deltaDesc);
375 return null;
376 }
377
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800378 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700379
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700380 final Device oldDevice = devices.get(deviceId);
381 final Device newDevice;
382
383 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700384 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700385 // on new device or valid update
386 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800387 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700388 } else {
389 // outdated event, ignored.
390 return null;
391 }
392 if (oldDevice == null) {
393 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700394 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700395 } else {
396 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700397 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700398 }
399 }
400 }
401
402 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700403 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700404 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700405 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700406
407 // update composed device cache
408 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
409 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700410 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
411 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700412
413 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700414 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700415 }
416
417 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
418 }
419
420 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700421 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700422 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700423 Device oldDevice,
424 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700425 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700426 boolean propertiesChanged =
427 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700428 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
429 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700430 boolean annotationsChanged =
431 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700432
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700433 // Primary providers can respond to all changes, but ancillary ones
434 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800435 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700436 if ((providerId.isAncillary() && annotationsChanged) ||
437 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700438 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
439 if (!replaced) {
440 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700441 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
442 providerId, oldDevice, devices.get(newDevice.id())
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700443 , newDevice);
444 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700445
alshabibdc5d8bd2015-11-02 15:41:29 -0800446 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700447 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800448
449 if (!providerId.isAncillary()) {
450 boolean wasOnline = availableDevices.contains(newDevice.id());
451 markOnline(newDevice.id(), newTimestamp);
452 if (!wasOnline) {
453 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
454 }
455 }
456 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700457 }
458
459 @Override
460 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700461 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700462 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700463 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700464 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700465 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800466 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700467 }
468 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700469 }
470
471 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
472
473 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700474 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700475
476 // locking device
477 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700478
479 // accept off-line if given timestamp is newer than
480 // the latest Timestamp from Primary provider
481 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
482 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
483 if (timestamp.compareTo(lastTimestamp) <= 0) {
484 // outdated event ignore
485 return null;
486 }
487
488 offline.put(deviceId, timestamp);
489
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700490 Device device = devices.get(deviceId);
491 if (device == null) {
492 return null;
493 }
494 boolean removed = availableDevices.remove(deviceId);
495 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700496 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700497 }
498 return null;
499 }
500 }
501
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700502 /**
503 * Marks the device as available if the given timestamp is not outdated,
504 * compared to the time the device has been marked offline.
505 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700506 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700507 * @param timestamp of the event triggering this change.
508 * @return true if availability change request was accepted and changed the state
509 */
510 // Guarded by deviceDescs value (=Device lock)
511 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
512 // accept on-line if given timestamp is newer than
513 // the latest offline request Timestamp
514 Timestamp offlineTimestamp = offline.get(deviceId);
515 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700516 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700517
518 offline.remove(deviceId);
519 return availableDevices.add(deviceId);
520 }
521 return false;
522 }
523
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700524 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700525 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700526 DeviceId deviceId,
527 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700528
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800529 NodeId localNode = clusterService.getLocalNode().id();
530 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
531 // since it will trigger distributed store read.
532 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
533 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
534 // If we don't care much about topology performance, then it might be OK.
535 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700536
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800537 // Process port update only if we're the master of the device,
538 // otherwise signal the actual master.
539 List<DeviceEvent> deviceEvents = null;
540 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700541
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800542 final Timestamp newTimestamp;
543 try {
544 newTimestamp = deviceClockService.getTimestamp(deviceId);
545 } catch (IllegalStateException e) {
546 log.info("Timestamp was not available for device {}", deviceId);
547 log.debug(" discarding {}", portDescriptions);
548 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700549
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800550 // Possible situation:
551 // Device connected and became master for short period of time,
552 // but lost mastership before this instance had the chance to
553 // retrieve term information.
554
555 // Information dropped here is expected to be recoverable by
556 // device probing after mastership change
557
558 return Collections.emptyList();
559 }
560 log.debug("timestamp for {} {}", deviceId, newTimestamp);
561
562 final Timestamped<List<PortDescription>> timestampedInput
563 = new Timestamped<>(portDescriptions, newTimestamp);
564 final Timestamped<List<PortDescription>> merged;
565
566 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
567
568 synchronized (device) {
569 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
570 final DeviceDescriptions descs = device.get(providerId);
571 List<PortDescription> mergedList =
572 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700573 .transform(input ->
574 // lookup merged port description
575 descs.getPortDesc(input.portNumber()).value()
576 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700577 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800578 }
579
580 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700581 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700582 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800583 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
584 }
585
586 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800587 // Only forward for ConfigProvider
588 // Forwarding was added as a workaround for ONOS-490
589 if (!providerId.equals("cfg")) {
590 return null;
591 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800592 // FIXME Temporary hack for NPE (ONOS-1171).
593 // Proper fix is to implement forwarding to master on ConfigProvider
594 // redo ONOS-490
595 if (deviceNode == null) {
596 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800597 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800598 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800599
600 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800601
602 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700603 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800604 /* error log:
605 log.warn("Failed to process injected ports of device id: {} " +
606 "(cluster messaging failed: {})",
607 deviceId, e);
608 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700609 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700610
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800611 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700612 }
613
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700614 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700615 DeviceId deviceId,
616 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700617
618 Device device = devices.get(deviceId);
619 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
620
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700621 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700622 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
623
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700624 List<DeviceEvent> events = new ArrayList<>();
625 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700626
627 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
628 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700629 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700630 }
631
632 DeviceDescriptions descs = descsMap.get(providerId);
633 // every provider must provide DeviceDescription.
634 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700635 "Device description for Device ID %s from Provider %s was not found",
636 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700637
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700638 Map<PortNumber, Port> ports = getPortMap(deviceId);
639
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700640 final Timestamp newTimestamp = portDescriptions.timestamp();
641
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700642 // Add new ports
643 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700644 for (PortDescription portDescription : portDescriptions.value()) {
645 final PortNumber number = portDescription.portNumber();
646 processed.add(number);
647
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700648 final Port oldPort = ports.get(number);
649 final Port newPort;
650
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700651
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700652 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
653 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700654 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700655 // on new port or valid update
656 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700657 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700658 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700659 newPort = composePort(device, number, descsMap);
660 } else {
661 // outdated event, ignored.
662 continue;
663 }
664
665 events.add(oldPort == null ?
666 createPort(device, newPort, ports) :
667 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700668 }
669
670 events.addAll(pruneOldPorts(device, ports, processed));
671 }
672 return FluentIterable.from(events).filter(notNull()).toList();
673 }
674
675 // Creates a new port based on the port description adds it to the map and
676 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700677 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700678 private DeviceEvent createPort(Device device, Port newPort,
679 Map<PortNumber, Port> ports) {
680 ports.put(newPort.number(), newPort);
681 return new DeviceEvent(PORT_ADDED, device, newPort);
682 }
683
684 // Checks if the specified port requires update and if so, it replaces the
685 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700686 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700687 private DeviceEvent updatePort(Device device, Port oldPort,
688 Port newPort,
689 Map<PortNumber, Port> ports) {
690 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700691 oldPort.type() != newPort.type() ||
692 oldPort.portSpeed() != newPort.portSpeed() ||
693 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700694 ports.put(oldPort.number(), newPort);
695 return new DeviceEvent(PORT_UPDATED, device, newPort);
696 }
697 return null;
698 }
699
700 // Prunes the specified list of ports based on which ports are in the
701 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700702 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700703 private List<DeviceEvent> pruneOldPorts(Device device,
704 Map<PortNumber, Port> ports,
705 Set<PortNumber> processed) {
706 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700707 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700708 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700709 Entry<PortNumber, Port> e = iterator.next();
710 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700711 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700712 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700713 iterator.remove();
714 }
715 }
716 return events;
717 }
718
719 // Gets the map of ports for the specified device; if one does not already
720 // exist, it creates and registers a new one.
721 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
722 return createIfAbsentUnchecked(devicePorts, deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700723 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700724 }
725
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700726 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700727 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700728 Map<ProviderId, DeviceDescriptions> r;
729 r = deviceDescs.get(deviceId);
730 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700731 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700732 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
733 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
734 if (concurrentlyAdded != null) {
735 r = concurrentlyAdded;
736 }
737 }
738 return r;
739 }
740
741 // Guarded by deviceDescs value (=Device lock)
742 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
743 Map<ProviderId, DeviceDescriptions> device,
744 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700745 synchronized (device) {
746 DeviceDescriptions r = device.get(providerId);
747 if (r == null) {
748 r = new DeviceDescriptions(deltaDesc);
749 device.put(providerId, r);
750 }
751 return r;
752 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700753 }
754
755 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700756 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
757 DeviceId deviceId,
758 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700759 final Timestamp newTimestamp;
760 try {
761 newTimestamp = deviceClockService.getTimestamp(deviceId);
762 } catch (IllegalStateException e) {
763 log.info("Timestamp was not available for device {}", deviceId);
764 log.debug(" discarding {}", portDescription);
765 // Failed to generate timestamp. Ignoring.
766 // See updatePorts comment
767 return null;
768 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700769 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700770 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700771 final DeviceEvent event;
772 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800773 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
774 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700775 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800776 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700777 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700778 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700779 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700780 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700781 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800782 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700783 }
784 return event;
785 }
786
787 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700788 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700789 Device device = devices.get(deviceId);
790 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
791
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700792 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700793 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
794
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700795 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700796
797 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
798 log.debug("Ignoring outdated event: {}", deltaDesc);
799 return null;
800 }
801
802 DeviceDescriptions descs = descsMap.get(providerId);
803 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700804 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700805 "Device description for Device ID %s from Provider %s was not found",
806 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700807
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700808 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
809 final PortNumber number = deltaDesc.value().portNumber();
810 final Port oldPort = ports.get(number);
811 final Port newPort;
812
813 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
814 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700815 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700816 // on new port or valid update
817 // update description
818 descs.putPortDesc(deltaDesc);
819 newPort = composePort(device, number, descsMap);
820 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700821 // same or outdated event, ignored.
822 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700823 return null;
824 }
825
826 if (oldPort == null) {
827 return createPort(device, newPort, ports);
828 } else {
829 return updatePort(device, oldPort, newPort, ports);
830 }
831 }
832 }
833
834 @Override
835 public List<Port> getPorts(DeviceId deviceId) {
836 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
837 if (ports == null) {
838 return Collections.emptyList();
839 }
840 return ImmutableList.copyOf(ports.values());
841 }
842
843 @Override
sangho538108b2015-04-08 14:29:20 -0700844 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200845 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700846
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200847 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
848 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
849 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
850
851 if (prvStatsMap != null) {
852 for (PortStatistics newStats : newStatsCollection) {
853 PortNumber port = PortNumber.portNumber(newStats.port());
854 PortStatistics prvStats = prvStatsMap.get(port);
855 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
856 PortStatistics deltaStats = builder.build();
857 if (prvStats != null) {
858 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
859 }
860 deltaStatsMap.put(port, deltaStats);
861 newStatsMap.put(port, newStats);
862 }
863 } else {
864 for (PortStatistics newStats : newStatsCollection) {
865 PortNumber port = PortNumber.portNumber(newStats.port());
866 newStatsMap.put(port, newStats);
867 }
sangho538108b2015-04-08 14:29:20 -0700868 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200869 devicePortDeltaStats.put(deviceId, deltaStatsMap);
870 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200871 // DeviceEvent returns null because of InternalPortStatsListener usage
872 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200873 }
874
875 /**
876 * Calculate delta statistics by subtracting previous from new statistics.
877 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700878 * @param deviceId device identifier
879 * @param prvStats previous port statistics
880 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200881 * @return PortStatistics
882 */
883 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
884 // calculate time difference
885 long deltaStatsSec, deltaStatsNano;
886 if (newStats.durationNano() < prvStats.durationNano()) {
887 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
888 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
889 } else {
890 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
891 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
892 }
893 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
894 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
895 .setPort(newStats.port())
896 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
897 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
898 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
899 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
900 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
901 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
902 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
903 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
904 .setDurationSec(deltaStatsSec)
905 .setDurationNano(deltaStatsNano)
906 .build();
907 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700908 }
909
910 @Override
911 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700912 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
913 if (portStats == null) {
914 return Collections.emptyList();
915 }
916 return ImmutableList.copyOf(portStats.values());
917 }
918
919 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200920 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
921 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
922 if (portStats == null) {
923 return Collections.emptyList();
924 }
925 return ImmutableList.copyOf(portStats.values());
926 }
927
928 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700929 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
930 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
931 return ports == null ? null : ports.get(portNumber);
932 }
933
934 @Override
935 public boolean isAvailable(DeviceId deviceId) {
936 return availableDevices.contains(deviceId);
937 }
938
939 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700940 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800941 final NodeId myId = clusterService.getLocalNode().id();
942 NodeId master = mastershipService.getMasterFor(deviceId);
943
944 // if there exist a master, forward
945 // if there is no master, try to become one and process
946
947 boolean relinquishAtEnd = false;
948 if (master == null) {
949 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
950 if (myRole != MastershipRole.NONE) {
951 relinquishAtEnd = true;
952 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800953 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800954 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800955 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700956 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800957 master = myId;
958 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700959 }
960
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800961 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800962 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700963 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800964
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800965 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700966 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800967 /* error log:
968 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
969 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800970
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800971 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700972 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800973 }
974
975 // I have control..
976
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700977 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700978 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700979 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800980 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700981 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800982 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700983 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800984 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800985 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800986 mastershipService.relinquishMastership(deviceId);
987 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700988 return event;
989 }
990
991 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
992 Timestamp timestamp) {
993
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700994 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700995 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700996 // accept removal request if given timestamp is newer than
997 // the latest Timestamp from Primary provider
998 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -0800999 if (primDescs == null) {
1000 return null;
1001 }
1002
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001003 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
1004 if (timestamp.compareTo(lastTimestamp) <= 0) {
1005 // outdated event ignore
1006 return null;
1007 }
1008 removalRequest.put(deviceId, timestamp);
1009
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001010 Device device = devices.remove(deviceId);
1011 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001012 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1013 if (ports != null) {
1014 ports.clear();
1015 }
1016 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001017 descs.clear();
1018 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001019 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001020 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001021 }
1022
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001023 /**
1024 * Checks if given timestamp is superseded by removal request
1025 * with more recent timestamp.
1026 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001027 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001028 * @param timestampToCheck timestamp of an event to check
1029 * @return true if device is already removed
1030 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001031 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1032 Timestamp removalTimestamp = removalRequest.get(deviceId);
1033 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001034 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001035 // removalRequest is more recent
1036 return true;
1037 }
1038 return false;
1039 }
1040
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001041 /**
1042 * Returns a Device, merging description given from multiple Providers.
1043 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001044 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001045 * @param providerDescs Collection of Descriptions from multiple providers
1046 * @return Device instance
1047 */
1048 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001049 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001050
Thomas Vachuska444eda62014-10-28 13:09:42 -07001051 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001052
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001053 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001054
1055 DeviceDescriptions desc = providerDescs.get(primary);
1056
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001057 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001058 Type type = base.type();
1059 String manufacturer = base.manufacturer();
1060 String hwVersion = base.hwVersion();
1061 String swVersion = base.swVersion();
1062 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001063 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001064 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1065 annotations = merge(annotations, base.annotations());
1066
1067 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1068 if (e.getKey().equals(primary)) {
1069 continue;
1070 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001071 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001072 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001073 // Currently assuming there will never be a key conflict between
1074 // providers
1075
1076 // annotation merging. not so efficient, should revisit later
1077 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1078 }
1079
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001080 return new DefaultDevice(primary, deviceId, type, manufacturer,
1081 hwVersion, swVersion, serialNumber,
1082 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001083 }
1084
Marc De Leenheer88194c32015-05-29 22:10:59 -07001085 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1086 PortDescription description, Annotations annotations) {
1087 switch (description.type()) {
1088 case OMS:
1089 OmsPortDescription omsDesc = (OmsPortDescription) description;
1090 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1091 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1092 case OCH:
1093 OchPortDescription ochDesc = (OchPortDescription) description;
1094 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1095 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1096 case ODUCLT:
1097 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1098 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1099 default:
1100 return new DefaultPort(device, number, isEnabled, description.type(),
1101 description.portSpeed(), annotations);
1102 }
1103 }
1104
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001105 /**
1106 * Returns a Port, merging description given from multiple Providers.
1107 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001108 * @param device device the port is on
1109 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001110 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001111 * @return Port instance
1112 */
1113 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001114 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001115
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001116 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001117 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001118 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001119 boolean isEnabled = false;
1120 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001121 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001122 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1123 if (portDesc != null) {
1124 isEnabled = portDesc.value().isEnabled();
1125 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001126 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001127 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001128 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001129 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001130 if (e.getKey().equals(primary)) {
1131 continue;
1132 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001133 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001134 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001135 // Currently assuming there will never be a key conflict between
1136 // providers
1137
1138 // annotation merging. not so efficient, should revisit later
1139 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1140 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001141 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1142 continue;
1143 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001144 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001145 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001146 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001147 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001148 }
1149 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001150 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001151 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001152 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001153 PortDescription current = portDesc.value();
1154 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001155 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001156 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001157 }
1158
1159 /**
1160 * @return primary ProviderID, or randomly chosen one if none exists
1161 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001162 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001163 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001164 ProviderId fallBackPrimary = null;
1165 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1166 if (!e.getKey().isAncillary()) {
1167 return e.getKey();
1168 } else if (fallBackPrimary == null) {
1169 // pick randomly as a fallback in case there is no primary
1170 fallBackPrimary = e.getKey();
1171 }
1172 }
1173 return fallBackPrimary;
1174 }
1175
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001176 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001177 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001178 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001179 return providerDescs.get(pid);
1180 }
1181
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001182 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001183 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001184 }
1185
Jonathan Hart7d656f42015-01-27 14:07:23 -08001186 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001187 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001188 }
Madan Jampani47c93732014-10-06 20:46:08 -07001189
Jonathan Hart7d656f42015-01-27 14:07:23 -08001190 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001191 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001192 }
1193
Jonathan Hart7d656f42015-01-27 14:07:23 -08001194 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001195 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001196 }
1197
Jonathan Hart7d656f42015-01-27 14:07:23 -08001198 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001199 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001200 }
1201
Jonathan Hart7d656f42015-01-27 14:07:23 -08001202 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001203 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001204 }
1205
Jonathan Hart7d656f42015-01-27 14:07:23 -08001206 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001207 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1208 }
1209
1210 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1211 try {
1212 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1213 } catch (IOException e) {
1214 log.error("Failed to send" + event + " to " + recipient, e);
1215 }
1216 }
1217
1218 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1219 try {
1220 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1221 } catch (IOException e) {
1222 log.error("Failed to send" + event + " to " + recipient, e);
1223 }
1224 }
1225
1226 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1227 try {
1228 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1229 } catch (IOException e) {
1230 log.error("Failed to send" + event + " to " + recipient, e);
1231 }
1232 }
1233
1234 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1235 try {
1236 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1237 } catch (IOException e) {
1238 log.error("Failed to send" + event + " to " + recipient, e);
1239 }
1240 }
1241
1242 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1243 try {
1244 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1245 } catch (IOException e) {
1246 log.error("Failed to send" + event + " to " + recipient, e);
1247 }
1248 }
1249
1250 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1251 final NodeId self = clusterService.getLocalNode().id();
1252
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001253 final int numDevices = deviceDescs.size();
1254 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1255 final int portsPerDevice = 8; // random factor to minimize reallocation
1256 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1257 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001258
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001259 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001260
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001261 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001262 synchronized (devDescs) {
1263
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001264 // send device offline timestamp
1265 Timestamp lOffline = this.offline.get(deviceId);
1266 if (lOffline != null) {
1267 adOffline.put(deviceId, lOffline);
1268 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001269
1270 for (Entry<ProviderId, DeviceDescriptions>
1271 prov : devDescs.entrySet()) {
1272
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001273 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001274 final ProviderId provId = prov.getKey();
1275 final DeviceDescriptions descs = prov.getValue();
1276
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001277 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001278 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001279
1280 for (Entry<PortNumber, Timestamped<PortDescription>>
1281 portDesc : descs.getPortDescs().entrySet()) {
1282
1283 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001284 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001285 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001286 }
1287 }
1288 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001289 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001290
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001291 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001292 }
1293
1294 /**
1295 * Responds to anti-entropy advertisement message.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001296 * <p/>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001297 * Notify sender about out-dated information using regular replication message.
1298 * Send back advertisement to sender if not in sync.
1299 *
1300 * @param advertisement to respond to
1301 */
1302 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1303
1304 final NodeId sender = advertisement.sender();
1305
1306 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1307 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1308 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1309
1310 // Fragments to request
1311 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1312 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1313
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001314 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001315 final DeviceId deviceId = de.getKey();
1316 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1317
1318 synchronized (lDevice) {
1319 // latestTimestamp across provider
1320 // Note: can be null initially
1321 Timestamp localLatest = offline.get(deviceId);
1322
1323 // handle device Ads
1324 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1325 final ProviderId provId = prov.getKey();
1326 final DeviceDescriptions lDeviceDescs = prov.getValue();
1327
1328 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1329
1330
1331 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1332 Timestamp advDevTimestamp = devAds.get(devFragId);
1333
Jonathan Hart403ea932015-02-20 16:23:00 -08001334 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1335 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001336 // remote does not have it or outdated, suggest
1337 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1338 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1339 // local is outdated, request
1340 reqDevices.add(devFragId);
1341 }
1342
1343 // handle port Ads
1344 for (Entry<PortNumber, Timestamped<PortDescription>>
1345 pe : lDeviceDescs.getPortDescs().entrySet()) {
1346
1347 final PortNumber num = pe.getKey();
1348 final Timestamped<PortDescription> lPort = pe.getValue();
1349
1350 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1351
1352 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001353 if (advPortTimestamp == null || lPort.isNewerThan(
1354 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001355 // remote does not have it or outdated, suggest
1356 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1357 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1358 // local is outdated, request
1359 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1360 reqPorts.add(portFragId);
1361 }
1362
1363 // remove port Ad already processed
1364 portAds.remove(portFragId);
1365 } // end local port loop
1366
1367 // remove device Ad already processed
1368 devAds.remove(devFragId);
1369
1370 // find latest and update
1371 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1372 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001373 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001374 localLatest = providerLatest;
1375 }
1376 } // end local provider loop
1377
1378 // checking if remote timestamp is more recent.
1379 Timestamp rOffline = offlineAds.get(deviceId);
1380 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001381 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001382 // remote offline timestamp suggests that the
1383 // device is off-line
1384 markOfflineInternal(deviceId, rOffline);
1385 }
1386
1387 Timestamp lOffline = offline.get(deviceId);
1388 if (lOffline != null && rOffline == null) {
1389 // locally offline, but remote is online, suggest offline
1390 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1391 }
1392
1393 // remove device offline Ad already processed
1394 offlineAds.remove(deviceId);
1395 } // end local device loop
1396 } // device lock
1397
1398 // If there is any Ads left, request them
1399 log.trace("Ads left {}, {}", devAds, portAds);
1400 reqDevices.addAll(devAds.keySet());
1401 reqPorts.addAll(portAds.keySet());
1402
1403 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1404 log.trace("Nothing to request to remote peer {}", sender);
1405 return;
1406 }
1407
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001408 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001409
1410 // 2-way Anti-Entropy for now
1411 try {
1412 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1413 } catch (IOException e) {
1414 log.error("Failed to send response advertisement to " + sender, e);
1415 }
1416
1417// Sketch of 3-way Anti-Entropy
1418// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1419// ClusterMessage message = new ClusterMessage(
1420// clusterService.getLocalNode().id(),
1421// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1422// SERIALIZER.encode(request));
1423//
1424// try {
1425// clusterCommunicator.unicast(message, advertisement.sender());
1426// } catch (IOException e) {
1427// log.error("Failed to send advertisement reply to "
1428// + advertisement.sender(), e);
1429// }
Madan Jampani47c93732014-10-06 20:46:08 -07001430 }
1431
Madan Jampani255a58b2014-10-09 12:08:20 -07001432 private void notifyDelegateIfNotNull(DeviceEvent event) {
1433 if (event != null) {
1434 notifyDelegate(event);
1435 }
1436 }
1437
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001438 private final class SendAdvertisementTask implements Runnable {
1439
1440 @Override
1441 public void run() {
1442 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001443 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001444 return;
1445 }
1446
1447 try {
1448 final NodeId self = clusterService.getLocalNode().id();
1449 Set<ControllerNode> nodes = clusterService.getNodes();
1450
1451 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1452 .transform(toNodeId())
1453 .toList();
1454
1455 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001456 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001457 return;
1458 }
1459
1460 NodeId peer;
1461 do {
1462 int idx = RandomUtils.nextInt(0, nodeIds.size());
1463 peer = nodeIds.get(idx);
1464 } while (peer.equals(self));
1465
1466 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1467
1468 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001469 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001470 return;
1471 }
1472
1473 try {
1474 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1475 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001476 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001477 return;
1478 }
1479 } catch (Exception e) {
1480 // catch all Exception to avoid Scheduled task being suppressed.
1481 log.error("Exception thrown while sending advertisement", e);
1482 }
1483 }
1484 }
1485
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001486 private final class InternalDeviceEventListener
1487 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001488 @Override
1489 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001490 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001491 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001492
Madan Jampani47c93732014-10-06 20:46:08 -07001493 ProviderId providerId = event.providerId();
1494 DeviceId deviceId = event.deviceId();
1495 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001496
Madan Jampani2af244a2015-02-22 13:12:01 -08001497 try {
1498 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1499 } catch (Exception e) {
1500 log.warn("Exception thrown handling device update", e);
1501 }
Madan Jampani47c93732014-10-06 20:46:08 -07001502 }
1503 }
1504
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001505 private final class InternalDeviceOfflineEventListener
1506 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001507 @Override
1508 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001509 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001510 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001511
1512 DeviceId deviceId = event.deviceId();
1513 Timestamp timestamp = event.timestamp();
1514
Madan Jampani2af244a2015-02-22 13:12:01 -08001515 try {
1516 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1517 } catch (Exception e) {
1518 log.warn("Exception thrown handling device offline", e);
1519 }
Madan Jampani25322532014-10-08 11:20:38 -07001520 }
1521 }
1522
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001523 private final class InternalRemoveRequestListener
1524 implements ClusterMessageHandler {
1525 @Override
1526 public void handle(ClusterMessage message) {
1527 log.debug("Received device remove request from peer: {}", message.sender());
1528 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001529
Madan Jampani2af244a2015-02-22 13:12:01 -08001530 try {
1531 removeDevice(did);
1532 } catch (Exception e) {
1533 log.warn("Exception thrown handling device remove", e);
1534 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001535 }
1536 }
1537
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001538 private final class InternalDeviceRemovedEventListener
1539 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001540 @Override
1541 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001542 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001543 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001544
1545 DeviceId deviceId = event.deviceId();
1546 Timestamp timestamp = event.timestamp();
1547
Madan Jampani2af244a2015-02-22 13:12:01 -08001548 try {
1549 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1550 } catch (Exception e) {
1551 log.warn("Exception thrown handling device removed", e);
1552 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001553 }
1554 }
1555
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001556 private final class InternalPortEventListener
1557 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001558 @Override
1559 public void handle(ClusterMessage message) {
1560
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001561 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001562 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001563
1564 ProviderId providerId = event.providerId();
1565 DeviceId deviceId = event.deviceId();
1566 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1567
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001568 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001569 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001570 // Note: dropped information will be recovered by anti-entropy
1571 return;
1572 }
1573
Madan Jampani2af244a2015-02-22 13:12:01 -08001574 try {
1575 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1576 } catch (Exception e) {
1577 log.warn("Exception thrown handling port update", e);
1578 }
Madan Jampani47c93732014-10-06 20:46:08 -07001579 }
1580 }
1581
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001582 private final class InternalPortStatusEventListener
1583 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001584 @Override
1585 public void handle(ClusterMessage message) {
1586
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001587 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001588 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001589
1590 ProviderId providerId = event.providerId();
1591 DeviceId deviceId = event.deviceId();
1592 Timestamped<PortDescription> portDescription = event.portDescription();
1593
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001594 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001595 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001596 // Note: dropped information will be recovered by anti-entropy
1597 return;
1598 }
1599
Madan Jampani2af244a2015-02-22 13:12:01 -08001600 try {
1601 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1602 } catch (Exception e) {
1603 log.warn("Exception thrown handling port update", e);
1604 }
Madan Jampani47c93732014-10-06 20:46:08 -07001605 }
1606 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001607
1608 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001609 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001610 @Override
1611 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001612 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001613 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001614 try {
1615 handleAdvertisement(advertisement);
1616 } catch (Exception e) {
1617 log.warn("Exception thrown handling Device advertisements.", e);
1618 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001619 }
1620 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001621
1622 private final class DeviceInjectedEventListener
1623 implements ClusterMessageHandler {
1624 @Override
1625 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001626 log.debug("Received injected device event from peer: {}", message.sender());
1627 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1628
1629 ProviderId providerId = event.providerId();
1630 DeviceId deviceId = event.deviceId();
1631 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001632 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1633 // workaround for ONOS-1208
1634 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1635 return;
1636 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001637
Madan Jampani2af244a2015-02-22 13:12:01 -08001638 try {
1639 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1640 } catch (Exception e) {
1641 log.warn("Exception thrown handling device injected event.", e);
1642 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001643 }
1644 }
1645
1646 private final class PortInjectedEventListener
1647 implements ClusterMessageHandler {
1648 @Override
1649 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001650 log.debug("Received injected port event from peer: {}", message.sender());
1651 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1652
1653 ProviderId providerId = event.providerId();
1654 DeviceId deviceId = event.deviceId();
1655 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001656 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1657 // workaround for ONOS-1208
1658 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1659 return;
1660 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001661
Madan Jampani2af244a2015-02-22 13:12:01 -08001662 try {
1663 updatePorts(providerId, deviceId, portDescriptions);
1664 } catch (Exception e) {
1665 log.warn("Exception thrown handling port injected event.", e);
1666 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001667 }
1668 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001669
1670 private class InternalPortStatsListener
1671 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1672 @Override
1673 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1674 if (event.type() == PUT) {
1675 Device device = devices.get(event.key());
1676 if (device != null) {
1677 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1678 }
1679 }
1680 }
1681 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001682}