blob: 14648a577b9cf62ed6239642b9569739a2742519 [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]",
Jian Li68c4fc42016-01-11 16:07:03 -0800442 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700443 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700444
alshabibdc5d8bd2015-11-02 15:41:29 -0800445 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700446 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800447
448 if (!providerId.isAncillary()) {
449 boolean wasOnline = availableDevices.contains(newDevice.id());
450 markOnline(newDevice.id(), newTimestamp);
451 if (!wasOnline) {
452 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
453 }
454 }
455 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700456 }
457
458 @Override
459 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700460 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700461 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700462 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700463 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700464 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800465 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700466 }
467 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700468 }
469
470 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
471
472 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700473 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700474
475 // locking device
476 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700477
478 // accept off-line if given timestamp is newer than
479 // the latest Timestamp from Primary provider
480 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
481 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
482 if (timestamp.compareTo(lastTimestamp) <= 0) {
483 // outdated event ignore
484 return null;
485 }
486
487 offline.put(deviceId, timestamp);
488
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700489 Device device = devices.get(deviceId);
490 if (device == null) {
491 return null;
492 }
493 boolean removed = availableDevices.remove(deviceId);
494 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700495 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700496 }
497 return null;
498 }
499 }
500
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700501 /**
502 * Marks the device as available if the given timestamp is not outdated,
503 * compared to the time the device has been marked offline.
504 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700505 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700506 * @param timestamp of the event triggering this change.
507 * @return true if availability change request was accepted and changed the state
508 */
509 // Guarded by deviceDescs value (=Device lock)
510 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
511 // accept on-line if given timestamp is newer than
512 // the latest offline request Timestamp
513 Timestamp offlineTimestamp = offline.get(deviceId);
514 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700515 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700516
517 offline.remove(deviceId);
518 return availableDevices.add(deviceId);
519 }
520 return false;
521 }
522
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700523 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700524 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700525 DeviceId deviceId,
526 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700527
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800528 NodeId localNode = clusterService.getLocalNode().id();
529 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
530 // since it will trigger distributed store read.
531 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
532 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
533 // If we don't care much about topology performance, then it might be OK.
534 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700535
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800536 // Process port update only if we're the master of the device,
537 // otherwise signal the actual master.
538 List<DeviceEvent> deviceEvents = null;
539 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700540
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800541 final Timestamp newTimestamp;
542 try {
543 newTimestamp = deviceClockService.getTimestamp(deviceId);
544 } catch (IllegalStateException e) {
545 log.info("Timestamp was not available for device {}", deviceId);
546 log.debug(" discarding {}", portDescriptions);
547 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700548
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800549 // Possible situation:
550 // Device connected and became master for short period of time,
551 // but lost mastership before this instance had the chance to
552 // retrieve term information.
553
554 // Information dropped here is expected to be recoverable by
555 // device probing after mastership change
556
557 return Collections.emptyList();
558 }
559 log.debug("timestamp for {} {}", deviceId, newTimestamp);
560
561 final Timestamped<List<PortDescription>> timestampedInput
562 = new Timestamped<>(portDescriptions, newTimestamp);
563 final Timestamped<List<PortDescription>> merged;
564
565 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
566
567 synchronized (device) {
568 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
569 final DeviceDescriptions descs = device.get(providerId);
570 List<PortDescription> mergedList =
571 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700572 .transform(input ->
573 // lookup merged port description
574 descs.getPortDesc(input.portNumber()).value()
575 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700576 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800577 }
578
579 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700580 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700581 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800582 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
583 }
584
585 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800586 // Only forward for ConfigProvider
587 // Forwarding was added as a workaround for ONOS-490
588 if (!providerId.equals("cfg")) {
589 return null;
590 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800591 // FIXME Temporary hack for NPE (ONOS-1171).
592 // Proper fix is to implement forwarding to master on ConfigProvider
593 // redo ONOS-490
594 if (deviceNode == null) {
595 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800596 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800597 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800598
599 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800600
601 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700602 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800603 /* error log:
604 log.warn("Failed to process injected ports of device id: {} " +
605 "(cluster messaging failed: {})",
606 deviceId, e);
607 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700608 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700609
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800610 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700611 }
612
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700613 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700614 DeviceId deviceId,
615 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700616
617 Device device = devices.get(deviceId);
618 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
619
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700620 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700621 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
622
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700623 List<DeviceEvent> events = new ArrayList<>();
624 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700625
626 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
627 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700628 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700629 }
630
631 DeviceDescriptions descs = descsMap.get(providerId);
632 // every provider must provide DeviceDescription.
633 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700634 "Device description for Device ID %s from Provider %s was not found",
635 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700636
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700637 Map<PortNumber, Port> ports = getPortMap(deviceId);
638
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700639 final Timestamp newTimestamp = portDescriptions.timestamp();
640
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700641 // Add new ports
642 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700643 for (PortDescription portDescription : portDescriptions.value()) {
644 final PortNumber number = portDescription.portNumber();
645 processed.add(number);
646
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700647 final Port oldPort = ports.get(number);
648 final Port newPort;
649
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700650
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700651 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
652 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700653 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700654 // on new port or valid update
655 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700656 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700657 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700658 newPort = composePort(device, number, descsMap);
659 } else {
660 // outdated event, ignored.
661 continue;
662 }
663
664 events.add(oldPort == null ?
665 createPort(device, newPort, ports) :
666 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700667 }
668
669 events.addAll(pruneOldPorts(device, ports, processed));
670 }
671 return FluentIterable.from(events).filter(notNull()).toList();
672 }
673
674 // Creates a new port based on the port description adds it to the map and
675 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700676 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700677 private DeviceEvent createPort(Device device, Port newPort,
678 Map<PortNumber, Port> ports) {
679 ports.put(newPort.number(), newPort);
680 return new DeviceEvent(PORT_ADDED, device, newPort);
681 }
682
683 // Checks if the specified port requires update and if so, it replaces the
684 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700685 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700686 private DeviceEvent updatePort(Device device, Port oldPort,
687 Port newPort,
688 Map<PortNumber, Port> ports) {
689 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700690 oldPort.type() != newPort.type() ||
691 oldPort.portSpeed() != newPort.portSpeed() ||
692 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700693 ports.put(oldPort.number(), newPort);
694 return new DeviceEvent(PORT_UPDATED, device, newPort);
695 }
696 return null;
697 }
698
699 // Prunes the specified list of ports based on which ports are in the
700 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700701 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700702 private List<DeviceEvent> pruneOldPorts(Device device,
703 Map<PortNumber, Port> ports,
704 Set<PortNumber> processed) {
705 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700706 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700707 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700708 Entry<PortNumber, Port> e = iterator.next();
709 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700710 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700711 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700712 iterator.remove();
713 }
714 }
715 return events;
716 }
717
718 // Gets the map of ports for the specified device; if one does not already
719 // exist, it creates and registers a new one.
720 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
721 return createIfAbsentUnchecked(devicePorts, deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700722 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700723 }
724
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700725 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700726 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700727 Map<ProviderId, DeviceDescriptions> r;
728 r = deviceDescs.get(deviceId);
729 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700730 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700731 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
732 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
733 if (concurrentlyAdded != null) {
734 r = concurrentlyAdded;
735 }
736 }
737 return r;
738 }
739
740 // Guarded by deviceDescs value (=Device lock)
741 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
742 Map<ProviderId, DeviceDescriptions> device,
743 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700744 synchronized (device) {
745 DeviceDescriptions r = device.get(providerId);
746 if (r == null) {
747 r = new DeviceDescriptions(deltaDesc);
748 device.put(providerId, r);
749 }
750 return r;
751 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700752 }
753
754 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700755 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
756 DeviceId deviceId,
757 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700758 final Timestamp newTimestamp;
759 try {
760 newTimestamp = deviceClockService.getTimestamp(deviceId);
761 } catch (IllegalStateException e) {
762 log.info("Timestamp was not available for device {}", deviceId);
763 log.debug(" discarding {}", portDescription);
764 // Failed to generate timestamp. Ignoring.
765 // See updatePorts comment
766 return null;
767 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700768 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700769 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700770 final DeviceEvent event;
771 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800772 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
773 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700774 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800775 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700776 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700777 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700778 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700779 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700780 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800781 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700782 }
783 return event;
784 }
785
786 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700787 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700788 Device device = devices.get(deviceId);
789 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
790
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700791 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700792 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
793
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700794 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700795
796 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
797 log.debug("Ignoring outdated event: {}", deltaDesc);
798 return null;
799 }
800
801 DeviceDescriptions descs = descsMap.get(providerId);
802 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700803 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700804 "Device description for Device ID %s from Provider %s was not found",
805 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700806
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700807 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
808 final PortNumber number = deltaDesc.value().portNumber();
809 final Port oldPort = ports.get(number);
810 final Port newPort;
811
812 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
813 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700814 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700815 // on new port or valid update
816 // update description
817 descs.putPortDesc(deltaDesc);
818 newPort = composePort(device, number, descsMap);
819 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700820 // same or outdated event, ignored.
821 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700822 return null;
823 }
824
825 if (oldPort == null) {
826 return createPort(device, newPort, ports);
827 } else {
828 return updatePort(device, oldPort, newPort, ports);
829 }
830 }
831 }
832
833 @Override
834 public List<Port> getPorts(DeviceId deviceId) {
835 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
836 if (ports == null) {
837 return Collections.emptyList();
838 }
839 return ImmutableList.copyOf(ports.values());
840 }
841
842 @Override
sangho538108b2015-04-08 14:29:20 -0700843 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200844 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700845
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200846 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
847 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
848 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
849
850 if (prvStatsMap != null) {
851 for (PortStatistics newStats : newStatsCollection) {
852 PortNumber port = PortNumber.portNumber(newStats.port());
853 PortStatistics prvStats = prvStatsMap.get(port);
854 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
855 PortStatistics deltaStats = builder.build();
856 if (prvStats != null) {
857 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
858 }
859 deltaStatsMap.put(port, deltaStats);
860 newStatsMap.put(port, newStats);
861 }
862 } else {
863 for (PortStatistics newStats : newStatsCollection) {
864 PortNumber port = PortNumber.portNumber(newStats.port());
865 newStatsMap.put(port, newStats);
866 }
sangho538108b2015-04-08 14:29:20 -0700867 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200868 devicePortDeltaStats.put(deviceId, deltaStatsMap);
869 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200870 // DeviceEvent returns null because of InternalPortStatsListener usage
871 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200872 }
873
874 /**
875 * Calculate delta statistics by subtracting previous from new statistics.
876 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700877 * @param deviceId device identifier
878 * @param prvStats previous port statistics
879 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200880 * @return PortStatistics
881 */
882 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
883 // calculate time difference
884 long deltaStatsSec, deltaStatsNano;
885 if (newStats.durationNano() < prvStats.durationNano()) {
886 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
887 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
888 } else {
889 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
890 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
891 }
892 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
893 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
894 .setPort(newStats.port())
895 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
896 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
897 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
898 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
899 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
900 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
901 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
902 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
903 .setDurationSec(deltaStatsSec)
904 .setDurationNano(deltaStatsNano)
905 .build();
906 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700907 }
908
909 @Override
910 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700911 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
912 if (portStats == null) {
913 return Collections.emptyList();
914 }
915 return ImmutableList.copyOf(portStats.values());
916 }
917
918 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200919 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
920 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
921 if (portStats == null) {
922 return Collections.emptyList();
923 }
924 return ImmutableList.copyOf(portStats.values());
925 }
926
927 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700928 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
929 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
930 return ports == null ? null : ports.get(portNumber);
931 }
932
933 @Override
934 public boolean isAvailable(DeviceId deviceId) {
935 return availableDevices.contains(deviceId);
936 }
937
938 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700939 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800940 final NodeId myId = clusterService.getLocalNode().id();
941 NodeId master = mastershipService.getMasterFor(deviceId);
942
943 // if there exist a master, forward
944 // if there is no master, try to become one and process
945
946 boolean relinquishAtEnd = false;
947 if (master == null) {
948 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
949 if (myRole != MastershipRole.NONE) {
950 relinquishAtEnd = true;
951 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800952 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800953 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800954 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700955 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800956 master = myId;
957 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700958 }
959
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800960 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800961 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700962 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800963
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800964 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700965 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800966 /* error log:
967 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
968 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800969
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800970 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700971 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800972 }
973
974 // I have control..
975
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700976 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700977 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700978 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800979 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700980 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800981 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700982 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800983 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800984 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800985 mastershipService.relinquishMastership(deviceId);
986 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700987 return event;
988 }
989
990 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
991 Timestamp timestamp) {
992
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700993 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700994 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700995 // accept removal request if given timestamp is newer than
996 // the latest Timestamp from Primary provider
997 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -0800998 if (primDescs == null) {
999 return null;
1000 }
1001
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001002 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
1003 if (timestamp.compareTo(lastTimestamp) <= 0) {
1004 // outdated event ignore
1005 return null;
1006 }
1007 removalRequest.put(deviceId, timestamp);
1008
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001009 Device device = devices.remove(deviceId);
1010 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001011 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1012 if (ports != null) {
1013 ports.clear();
1014 }
1015 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001016 descs.clear();
1017 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001018 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001019 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001020 }
1021
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001022 /**
1023 * Checks if given timestamp is superseded by removal request
1024 * with more recent timestamp.
1025 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001026 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001027 * @param timestampToCheck timestamp of an event to check
1028 * @return true if device is already removed
1029 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001030 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1031 Timestamp removalTimestamp = removalRequest.get(deviceId);
1032 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001033 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001034 // removalRequest is more recent
1035 return true;
1036 }
1037 return false;
1038 }
1039
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001040 /**
1041 * Returns a Device, merging description given from multiple Providers.
1042 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001043 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001044 * @param providerDescs Collection of Descriptions from multiple providers
1045 * @return Device instance
1046 */
1047 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001048 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001049
Thomas Vachuska444eda62014-10-28 13:09:42 -07001050 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001051
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001052 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001053
1054 DeviceDescriptions desc = providerDescs.get(primary);
1055
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001056 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001057 Type type = base.type();
1058 String manufacturer = base.manufacturer();
1059 String hwVersion = base.hwVersion();
1060 String swVersion = base.swVersion();
1061 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001062 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001063 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1064 annotations = merge(annotations, base.annotations());
1065
1066 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1067 if (e.getKey().equals(primary)) {
1068 continue;
1069 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001070 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001071 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001072 // Currently assuming there will never be a key conflict between
1073 // providers
1074
1075 // annotation merging. not so efficient, should revisit later
1076 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1077 }
1078
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001079 return new DefaultDevice(primary, deviceId, type, manufacturer,
1080 hwVersion, swVersion, serialNumber,
1081 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001082 }
1083
Marc De Leenheer88194c32015-05-29 22:10:59 -07001084 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1085 PortDescription description, Annotations annotations) {
1086 switch (description.type()) {
1087 case OMS:
1088 OmsPortDescription omsDesc = (OmsPortDescription) description;
1089 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1090 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1091 case OCH:
1092 OchPortDescription ochDesc = (OchPortDescription) description;
1093 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1094 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1095 case ODUCLT:
1096 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1097 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1098 default:
1099 return new DefaultPort(device, number, isEnabled, description.type(),
1100 description.portSpeed(), annotations);
1101 }
1102 }
1103
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001104 /**
1105 * Returns a Port, merging description given from multiple Providers.
1106 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001107 * @param device device the port is on
1108 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001109 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001110 * @return Port instance
1111 */
1112 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001113 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001114
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001115 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001116 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001117 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001118 boolean isEnabled = false;
1119 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001120 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001121 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1122 if (portDesc != null) {
1123 isEnabled = portDesc.value().isEnabled();
1124 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001125 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001126 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001127 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001128 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001129 if (e.getKey().equals(primary)) {
1130 continue;
1131 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001132 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001133 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001134 // Currently assuming there will never be a key conflict between
1135 // providers
1136
1137 // annotation merging. not so efficient, should revisit later
1138 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1139 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001140 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1141 continue;
1142 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001143 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001144 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001145 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001146 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001147 }
1148 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001149 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001150 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001151 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001152 PortDescription current = portDesc.value();
1153 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001154 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001155 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001156 }
1157
1158 /**
1159 * @return primary ProviderID, or randomly chosen one if none exists
1160 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001161 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001162 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001163 ProviderId fallBackPrimary = null;
1164 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1165 if (!e.getKey().isAncillary()) {
1166 return e.getKey();
1167 } else if (fallBackPrimary == null) {
1168 // pick randomly as a fallback in case there is no primary
1169 fallBackPrimary = e.getKey();
1170 }
1171 }
1172 return fallBackPrimary;
1173 }
1174
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001175 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001176 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001177 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001178 return providerDescs.get(pid);
1179 }
1180
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001181 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001182 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001183 }
1184
Jonathan Hart7d656f42015-01-27 14:07:23 -08001185 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001186 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001187 }
Madan Jampani47c93732014-10-06 20:46:08 -07001188
Jonathan Hart7d656f42015-01-27 14:07:23 -08001189 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001190 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001191 }
1192
Jonathan Hart7d656f42015-01-27 14:07:23 -08001193 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001194 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001195 }
1196
Jonathan Hart7d656f42015-01-27 14:07:23 -08001197 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001198 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001199 }
1200
Jonathan Hart7d656f42015-01-27 14:07:23 -08001201 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001202 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001203 }
1204
Jonathan Hart7d656f42015-01-27 14:07:23 -08001205 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001206 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1207 }
1208
1209 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1210 try {
1211 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1212 } catch (IOException e) {
1213 log.error("Failed to send" + event + " to " + recipient, e);
1214 }
1215 }
1216
1217 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1218 try {
1219 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1220 } catch (IOException e) {
1221 log.error("Failed to send" + event + " to " + recipient, e);
1222 }
1223 }
1224
1225 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1226 try {
1227 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1228 } catch (IOException e) {
1229 log.error("Failed to send" + event + " to " + recipient, e);
1230 }
1231 }
1232
1233 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1234 try {
1235 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1236 } catch (IOException e) {
1237 log.error("Failed to send" + event + " to " + recipient, e);
1238 }
1239 }
1240
1241 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1242 try {
1243 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1244 } catch (IOException e) {
1245 log.error("Failed to send" + event + " to " + recipient, e);
1246 }
1247 }
1248
1249 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1250 final NodeId self = clusterService.getLocalNode().id();
1251
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001252 final int numDevices = deviceDescs.size();
1253 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1254 final int portsPerDevice = 8; // random factor to minimize reallocation
1255 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1256 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001257
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001258 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001259
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001260 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001261 synchronized (devDescs) {
1262
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001263 // send device offline timestamp
1264 Timestamp lOffline = this.offline.get(deviceId);
1265 if (lOffline != null) {
1266 adOffline.put(deviceId, lOffline);
1267 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001268
1269 for (Entry<ProviderId, DeviceDescriptions>
1270 prov : devDescs.entrySet()) {
1271
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001272 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001273 final ProviderId provId = prov.getKey();
1274 final DeviceDescriptions descs = prov.getValue();
1275
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001276 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001277 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001278
1279 for (Entry<PortNumber, Timestamped<PortDescription>>
1280 portDesc : descs.getPortDescs().entrySet()) {
1281
1282 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001283 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001284 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001285 }
1286 }
1287 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001288 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001289
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001290 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001291 }
1292
1293 /**
1294 * Responds to anti-entropy advertisement message.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001295 * <p/>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001296 * Notify sender about out-dated information using regular replication message.
1297 * Send back advertisement to sender if not in sync.
1298 *
1299 * @param advertisement to respond to
1300 */
1301 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1302
1303 final NodeId sender = advertisement.sender();
1304
1305 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1306 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1307 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1308
1309 // Fragments to request
1310 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1311 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1312
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001313 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001314 final DeviceId deviceId = de.getKey();
1315 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1316
1317 synchronized (lDevice) {
1318 // latestTimestamp across provider
1319 // Note: can be null initially
1320 Timestamp localLatest = offline.get(deviceId);
1321
1322 // handle device Ads
1323 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1324 final ProviderId provId = prov.getKey();
1325 final DeviceDescriptions lDeviceDescs = prov.getValue();
1326
1327 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1328
1329
1330 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1331 Timestamp advDevTimestamp = devAds.get(devFragId);
1332
Jonathan Hart403ea932015-02-20 16:23:00 -08001333 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1334 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001335 // remote does not have it or outdated, suggest
1336 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1337 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1338 // local is outdated, request
1339 reqDevices.add(devFragId);
1340 }
1341
1342 // handle port Ads
1343 for (Entry<PortNumber, Timestamped<PortDescription>>
1344 pe : lDeviceDescs.getPortDescs().entrySet()) {
1345
1346 final PortNumber num = pe.getKey();
1347 final Timestamped<PortDescription> lPort = pe.getValue();
1348
1349 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1350
1351 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001352 if (advPortTimestamp == null || lPort.isNewerThan(
1353 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001354 // remote does not have it or outdated, suggest
1355 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1356 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1357 // local is outdated, request
1358 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1359 reqPorts.add(portFragId);
1360 }
1361
1362 // remove port Ad already processed
1363 portAds.remove(portFragId);
1364 } // end local port loop
1365
1366 // remove device Ad already processed
1367 devAds.remove(devFragId);
1368
1369 // find latest and update
1370 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1371 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001372 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001373 localLatest = providerLatest;
1374 }
1375 } // end local provider loop
1376
1377 // checking if remote timestamp is more recent.
1378 Timestamp rOffline = offlineAds.get(deviceId);
1379 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001380 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001381 // remote offline timestamp suggests that the
1382 // device is off-line
1383 markOfflineInternal(deviceId, rOffline);
1384 }
1385
1386 Timestamp lOffline = offline.get(deviceId);
1387 if (lOffline != null && rOffline == null) {
1388 // locally offline, but remote is online, suggest offline
1389 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1390 }
1391
1392 // remove device offline Ad already processed
1393 offlineAds.remove(deviceId);
1394 } // end local device loop
1395 } // device lock
1396
1397 // If there is any Ads left, request them
1398 log.trace("Ads left {}, {}", devAds, portAds);
1399 reqDevices.addAll(devAds.keySet());
1400 reqPorts.addAll(portAds.keySet());
1401
1402 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1403 log.trace("Nothing to request to remote peer {}", sender);
1404 return;
1405 }
1406
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001407 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001408
1409 // 2-way Anti-Entropy for now
1410 try {
1411 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1412 } catch (IOException e) {
1413 log.error("Failed to send response advertisement to " + sender, e);
1414 }
1415
1416// Sketch of 3-way Anti-Entropy
1417// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1418// ClusterMessage message = new ClusterMessage(
1419// clusterService.getLocalNode().id(),
1420// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1421// SERIALIZER.encode(request));
1422//
1423// try {
1424// clusterCommunicator.unicast(message, advertisement.sender());
1425// } catch (IOException e) {
1426// log.error("Failed to send advertisement reply to "
1427// + advertisement.sender(), e);
1428// }
Madan Jampani47c93732014-10-06 20:46:08 -07001429 }
1430
Madan Jampani255a58b2014-10-09 12:08:20 -07001431 private void notifyDelegateIfNotNull(DeviceEvent event) {
1432 if (event != null) {
1433 notifyDelegate(event);
1434 }
1435 }
1436
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001437 private final class SendAdvertisementTask implements Runnable {
1438
1439 @Override
1440 public void run() {
1441 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001442 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001443 return;
1444 }
1445
1446 try {
1447 final NodeId self = clusterService.getLocalNode().id();
1448 Set<ControllerNode> nodes = clusterService.getNodes();
1449
1450 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1451 .transform(toNodeId())
1452 .toList();
1453
1454 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001455 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001456 return;
1457 }
1458
1459 NodeId peer;
1460 do {
1461 int idx = RandomUtils.nextInt(0, nodeIds.size());
1462 peer = nodeIds.get(idx);
1463 } while (peer.equals(self));
1464
1465 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1466
1467 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001468 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001469 return;
1470 }
1471
1472 try {
1473 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1474 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001475 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001476 return;
1477 }
1478 } catch (Exception e) {
1479 // catch all Exception to avoid Scheduled task being suppressed.
1480 log.error("Exception thrown while sending advertisement", e);
1481 }
1482 }
1483 }
1484
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001485 private final class InternalDeviceEventListener
1486 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001487 @Override
1488 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001489 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001490 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001491
Madan Jampani47c93732014-10-06 20:46:08 -07001492 ProviderId providerId = event.providerId();
1493 DeviceId deviceId = event.deviceId();
1494 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001495
Madan Jampani2af244a2015-02-22 13:12:01 -08001496 try {
1497 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1498 } catch (Exception e) {
1499 log.warn("Exception thrown handling device update", e);
1500 }
Madan Jampani47c93732014-10-06 20:46:08 -07001501 }
1502 }
1503
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001504 private final class InternalDeviceOfflineEventListener
1505 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001506 @Override
1507 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001508 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001509 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001510
1511 DeviceId deviceId = event.deviceId();
1512 Timestamp timestamp = event.timestamp();
1513
Madan Jampani2af244a2015-02-22 13:12:01 -08001514 try {
1515 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1516 } catch (Exception e) {
1517 log.warn("Exception thrown handling device offline", e);
1518 }
Madan Jampani25322532014-10-08 11:20:38 -07001519 }
1520 }
1521
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001522 private final class InternalRemoveRequestListener
1523 implements ClusterMessageHandler {
1524 @Override
1525 public void handle(ClusterMessage message) {
1526 log.debug("Received device remove request from peer: {}", message.sender());
1527 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001528
Madan Jampani2af244a2015-02-22 13:12:01 -08001529 try {
1530 removeDevice(did);
1531 } catch (Exception e) {
1532 log.warn("Exception thrown handling device remove", e);
1533 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001534 }
1535 }
1536
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001537 private final class InternalDeviceRemovedEventListener
1538 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001539 @Override
1540 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001541 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001542 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001543
1544 DeviceId deviceId = event.deviceId();
1545 Timestamp timestamp = event.timestamp();
1546
Madan Jampani2af244a2015-02-22 13:12:01 -08001547 try {
1548 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1549 } catch (Exception e) {
1550 log.warn("Exception thrown handling device removed", e);
1551 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001552 }
1553 }
1554
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001555 private final class InternalPortEventListener
1556 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001557 @Override
1558 public void handle(ClusterMessage message) {
1559
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001560 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001561 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001562
1563 ProviderId providerId = event.providerId();
1564 DeviceId deviceId = event.deviceId();
1565 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1566
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001567 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001568 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001569 // Note: dropped information will be recovered by anti-entropy
1570 return;
1571 }
1572
Madan Jampani2af244a2015-02-22 13:12:01 -08001573 try {
1574 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1575 } catch (Exception e) {
1576 log.warn("Exception thrown handling port update", e);
1577 }
Madan Jampani47c93732014-10-06 20:46:08 -07001578 }
1579 }
1580
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001581 private final class InternalPortStatusEventListener
1582 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001583 @Override
1584 public void handle(ClusterMessage message) {
1585
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001586 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001587 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001588
1589 ProviderId providerId = event.providerId();
1590 DeviceId deviceId = event.deviceId();
1591 Timestamped<PortDescription> portDescription = event.portDescription();
1592
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001593 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001594 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001595 // Note: dropped information will be recovered by anti-entropy
1596 return;
1597 }
1598
Madan Jampani2af244a2015-02-22 13:12:01 -08001599 try {
1600 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1601 } catch (Exception e) {
1602 log.warn("Exception thrown handling port update", e);
1603 }
Madan Jampani47c93732014-10-06 20:46:08 -07001604 }
1605 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001606
1607 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001608 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001609 @Override
1610 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001611 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001612 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001613 try {
1614 handleAdvertisement(advertisement);
1615 } catch (Exception e) {
1616 log.warn("Exception thrown handling Device advertisements.", e);
1617 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001618 }
1619 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001620
1621 private final class DeviceInjectedEventListener
1622 implements ClusterMessageHandler {
1623 @Override
1624 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001625 log.debug("Received injected device event from peer: {}", message.sender());
1626 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1627
1628 ProviderId providerId = event.providerId();
1629 DeviceId deviceId = event.deviceId();
1630 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001631 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1632 // workaround for ONOS-1208
1633 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1634 return;
1635 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001636
Madan Jampani2af244a2015-02-22 13:12:01 -08001637 try {
1638 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1639 } catch (Exception e) {
1640 log.warn("Exception thrown handling device injected event.", e);
1641 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001642 }
1643 }
1644
1645 private final class PortInjectedEventListener
1646 implements ClusterMessageHandler {
1647 @Override
1648 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001649 log.debug("Received injected port event from peer: {}", message.sender());
1650 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1651
1652 ProviderId providerId = event.providerId();
1653 DeviceId deviceId = event.deviceId();
1654 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001655 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1656 // workaround for ONOS-1208
1657 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1658 return;
1659 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001660
Madan Jampani2af244a2015-02-22 13:12:01 -08001661 try {
1662 updatePorts(providerId, deviceId, portDescriptions);
1663 } catch (Exception e) {
1664 log.warn("Exception thrown handling port injected event.", e);
1665 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001666 }
1667 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001668
1669 private class InternalPortStatsListener
1670 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1671 @Override
1672 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1673 if (event.type() == PUT) {
1674 Device device = devices.get(event.key());
1675 if (device != null) {
1676 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1677 }
1678 }
1679 }
1680 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001681}