blob: 973db494b2376f59de18ff24342bfe6fa3341c8e [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 Yutadc2e7c22015-02-24 12:19:47 -0800333 // FIXME Temporary hack for NPE (ONOS-1171).
334 // Proper fix is to implement forwarding to master on ConfigProvider
335 // redo ONOS-490
336 if (deviceNode == null) {
337 // silently ignore
338 return null;
339 }
340
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800341
342 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
343 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800344
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800345 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700346 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800347 /* error log:
348 log.warn("Failed to process injected device id: {} desc: {} " +
349 "(cluster messaging failed: {})",
350 deviceId, deviceDescription, e);
351 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700352 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800353
354 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700355 }
356
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700357 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700358 DeviceId deviceId,
359 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700360
361 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800362 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700363 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700364
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800365 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700366 // locking per device
367
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700368 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
369 log.debug("Ignoring outdated event: {}", deltaDesc);
370 return null;
371 }
372
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800373 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700374
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700375 final Device oldDevice = devices.get(deviceId);
376 final Device newDevice;
377
378 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700379 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700380 // on new device or valid update
381 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800382 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700383 } else {
384 // outdated event, ignored.
385 return null;
386 }
387 if (oldDevice == null) {
388 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700389 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700390 } else {
391 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700392 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700393 }
394 }
395 }
396
397 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700398 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700399 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700400 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700401
402 // update composed device cache
403 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
404 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700405 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
406 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700407
408 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700409 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700410 }
411
412 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
413 }
414
415 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700416 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700417 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700418 Device oldDevice,
419 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700420 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700421 boolean propertiesChanged =
422 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700423 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
424 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700425 boolean annotationsChanged =
426 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700427
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700428 // Primary providers can respond to all changes, but ancillary ones
429 // should respond only to annotation changes.
430 if ((providerId.isAncillary() && annotationsChanged) ||
431 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700432 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
433 if (!replaced) {
434 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700435 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
436 providerId, oldDevice, devices.get(newDevice.id())
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700437 , newDevice);
438 }
439 if (!providerId.isAncillary()) {
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700440 boolean wasOnline = availableDevices.contains(newDevice.id());
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700441 markOnline(newDevice.id(), newTimestamp);
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700442 if (!wasOnline) {
443 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
444 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700445 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700446
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700447 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700448 }
449 return null;
450 }
451
452 @Override
453 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700454 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700455 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700456 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700457 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700458 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800459 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700460 }
461 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700462 }
463
464 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
465
466 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700467 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700468
469 // locking device
470 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700471
472 // accept off-line if given timestamp is newer than
473 // the latest Timestamp from Primary provider
474 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
475 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
476 if (timestamp.compareTo(lastTimestamp) <= 0) {
477 // outdated event ignore
478 return null;
479 }
480
481 offline.put(deviceId, timestamp);
482
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700483 Device device = devices.get(deviceId);
484 if (device == null) {
485 return null;
486 }
487 boolean removed = availableDevices.remove(deviceId);
488 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700489 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700490 }
491 return null;
492 }
493 }
494
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700495 /**
496 * Marks the device as available if the given timestamp is not outdated,
497 * compared to the time the device has been marked offline.
498 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700499 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700500 * @param timestamp of the event triggering this change.
501 * @return true if availability change request was accepted and changed the state
502 */
503 // Guarded by deviceDescs value (=Device lock)
504 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
505 // accept on-line if given timestamp is newer than
506 // the latest offline request Timestamp
507 Timestamp offlineTimestamp = offline.get(deviceId);
508 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700509 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700510
511 offline.remove(deviceId);
512 return availableDevices.add(deviceId);
513 }
514 return false;
515 }
516
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700517 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700518 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700519 DeviceId deviceId,
520 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700521
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800522 NodeId localNode = clusterService.getLocalNode().id();
523 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
524 // since it will trigger distributed store read.
525 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
526 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
527 // If we don't care much about topology performance, then it might be OK.
528 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700529
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800530 // Process port update only if we're the master of the device,
531 // otherwise signal the actual master.
532 List<DeviceEvent> deviceEvents = null;
533 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700534
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800535 final Timestamp newTimestamp;
536 try {
537 newTimestamp = deviceClockService.getTimestamp(deviceId);
538 } catch (IllegalStateException e) {
539 log.info("Timestamp was not available for device {}", deviceId);
540 log.debug(" discarding {}", portDescriptions);
541 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700542
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800543 // Possible situation:
544 // Device connected and became master for short period of time,
545 // but lost mastership before this instance had the chance to
546 // retrieve term information.
547
548 // Information dropped here is expected to be recoverable by
549 // device probing after mastership change
550
551 return Collections.emptyList();
552 }
553 log.debug("timestamp for {} {}", deviceId, newTimestamp);
554
555 final Timestamped<List<PortDescription>> timestampedInput
556 = new Timestamped<>(portDescriptions, newTimestamp);
557 final Timestamped<List<PortDescription>> merged;
558
559 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
560
561 synchronized (device) {
562 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
563 final DeviceDescriptions descs = device.get(providerId);
564 List<PortDescription> mergedList =
565 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700566 .transform(input ->
567 // lookup merged port description
568 descs.getPortDesc(input.portNumber()).value()
569 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700570 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800571 }
572
573 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700574 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700575 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800576 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
577 }
578
579 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800580 // FIXME Temporary hack for NPE (ONOS-1171).
581 // Proper fix is to implement forwarding to master on ConfigProvider
582 // redo ONOS-490
583 if (deviceNode == null) {
584 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800585 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800586 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800587
588 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800589
590 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700591 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800592 /* error log:
593 log.warn("Failed to process injected ports of device id: {} " +
594 "(cluster messaging failed: {})",
595 deviceId, e);
596 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700597 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700598
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800599 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700600 }
601
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700602 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700603 DeviceId deviceId,
604 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700605
606 Device device = devices.get(deviceId);
607 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
608
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700609 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700610 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
611
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700612 List<DeviceEvent> events = new ArrayList<>();
613 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700614
615 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
616 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700617 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700618 }
619
620 DeviceDescriptions descs = descsMap.get(providerId);
621 // every provider must provide DeviceDescription.
622 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700623 "Device description for Device ID %s from Provider %s was not found",
624 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700625
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700626 Map<PortNumber, Port> ports = getPortMap(deviceId);
627
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700628 final Timestamp newTimestamp = portDescriptions.timestamp();
629
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700630 // Add new ports
631 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700632 for (PortDescription portDescription : portDescriptions.value()) {
633 final PortNumber number = portDescription.portNumber();
634 processed.add(number);
635
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700636 final Port oldPort = ports.get(number);
637 final Port newPort;
638
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700639
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700640 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
641 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700642 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700643 // on new port or valid update
644 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700645 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700646 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700647 newPort = composePort(device, number, descsMap);
648 } else {
649 // outdated event, ignored.
650 continue;
651 }
652
653 events.add(oldPort == null ?
654 createPort(device, newPort, ports) :
655 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700656 }
657
658 events.addAll(pruneOldPorts(device, ports, processed));
659 }
660 return FluentIterable.from(events).filter(notNull()).toList();
661 }
662
663 // Creates a new port based on the port description adds it to the map and
664 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700665 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700666 private DeviceEvent createPort(Device device, Port newPort,
667 Map<PortNumber, Port> ports) {
668 ports.put(newPort.number(), newPort);
669 return new DeviceEvent(PORT_ADDED, device, newPort);
670 }
671
672 // Checks if the specified port requires update and if so, it replaces the
673 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700674 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700675 private DeviceEvent updatePort(Device device, Port oldPort,
676 Port newPort,
677 Map<PortNumber, Port> ports) {
678 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700679 oldPort.type() != newPort.type() ||
680 oldPort.portSpeed() != newPort.portSpeed() ||
681 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700682 ports.put(oldPort.number(), newPort);
683 return new DeviceEvent(PORT_UPDATED, device, newPort);
684 }
685 return null;
686 }
687
688 // Prunes the specified list of ports based on which ports are in the
689 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700690 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700691 private List<DeviceEvent> pruneOldPorts(Device device,
692 Map<PortNumber, Port> ports,
693 Set<PortNumber> processed) {
694 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700695 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700696 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700697 Entry<PortNumber, Port> e = iterator.next();
698 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700699 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700700 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700701 iterator.remove();
702 }
703 }
704 return events;
705 }
706
707 // Gets the map of ports for the specified device; if one does not already
708 // exist, it creates and registers a new one.
709 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
710 return createIfAbsentUnchecked(devicePorts, deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700711 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700712 }
713
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700714 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700715 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700716 Map<ProviderId, DeviceDescriptions> r;
717 r = deviceDescs.get(deviceId);
718 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700719 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700720 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
721 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
722 if (concurrentlyAdded != null) {
723 r = concurrentlyAdded;
724 }
725 }
726 return r;
727 }
728
729 // Guarded by deviceDescs value (=Device lock)
730 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
731 Map<ProviderId, DeviceDescriptions> device,
732 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700733 synchronized (device) {
734 DeviceDescriptions r = device.get(providerId);
735 if (r == null) {
736 r = new DeviceDescriptions(deltaDesc);
737 device.put(providerId, r);
738 }
739 return r;
740 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700741 }
742
743 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700744 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
745 DeviceId deviceId,
746 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700747 final Timestamp newTimestamp;
748 try {
749 newTimestamp = deviceClockService.getTimestamp(deviceId);
750 } catch (IllegalStateException e) {
751 log.info("Timestamp was not available for device {}", deviceId);
752 log.debug(" discarding {}", portDescription);
753 // Failed to generate timestamp. Ignoring.
754 // See updatePorts comment
755 return null;
756 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700757 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700758 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700759 final DeviceEvent event;
760 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800761 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
762 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700763 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800764 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700765 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700766 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700767 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700768 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700769 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800770 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700771 }
772 return event;
773 }
774
775 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700776 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700777 Device device = devices.get(deviceId);
778 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
779
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700780 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700781 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
782
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700783 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700784
785 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
786 log.debug("Ignoring outdated event: {}", deltaDesc);
787 return null;
788 }
789
790 DeviceDescriptions descs = descsMap.get(providerId);
791 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700792 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700793 "Device description for Device ID %s from Provider %s was not found",
794 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700795
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700796 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
797 final PortNumber number = deltaDesc.value().portNumber();
798 final Port oldPort = ports.get(number);
799 final Port newPort;
800
801 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
802 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700803 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700804 // on new port or valid update
805 // update description
806 descs.putPortDesc(deltaDesc);
807 newPort = composePort(device, number, descsMap);
808 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700809 // same or outdated event, ignored.
810 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700811 return null;
812 }
813
814 if (oldPort == null) {
815 return createPort(device, newPort, ports);
816 } else {
817 return updatePort(device, oldPort, newPort, ports);
818 }
819 }
820 }
821
822 @Override
823 public List<Port> getPorts(DeviceId deviceId) {
824 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
825 if (ports == null) {
826 return Collections.emptyList();
827 }
828 return ImmutableList.copyOf(ports.values());
829 }
830
831 @Override
sangho538108b2015-04-08 14:29:20 -0700832 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200833 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700834
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200835 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
836 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
837 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
838
839 if (prvStatsMap != null) {
840 for (PortStatistics newStats : newStatsCollection) {
841 PortNumber port = PortNumber.portNumber(newStats.port());
842 PortStatistics prvStats = prvStatsMap.get(port);
843 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
844 PortStatistics deltaStats = builder.build();
845 if (prvStats != null) {
846 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
847 }
848 deltaStatsMap.put(port, deltaStats);
849 newStatsMap.put(port, newStats);
850 }
851 } else {
852 for (PortStatistics newStats : newStatsCollection) {
853 PortNumber port = PortNumber.portNumber(newStats.port());
854 newStatsMap.put(port, newStats);
855 }
sangho538108b2015-04-08 14:29:20 -0700856 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200857 devicePortDeltaStats.put(deviceId, deltaStatsMap);
858 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200859 // DeviceEvent returns null because of InternalPortStatsListener usage
860 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200861 }
862
863 /**
864 * Calculate delta statistics by subtracting previous from new statistics.
865 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700866 * @param deviceId device identifier
867 * @param prvStats previous port statistics
868 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200869 * @return PortStatistics
870 */
871 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
872 // calculate time difference
873 long deltaStatsSec, deltaStatsNano;
874 if (newStats.durationNano() < prvStats.durationNano()) {
875 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
876 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
877 } else {
878 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
879 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
880 }
881 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
882 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
883 .setPort(newStats.port())
884 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
885 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
886 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
887 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
888 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
889 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
890 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
891 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
892 .setDurationSec(deltaStatsSec)
893 .setDurationNano(deltaStatsNano)
894 .build();
895 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700896 }
897
898 @Override
899 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700900 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
901 if (portStats == null) {
902 return Collections.emptyList();
903 }
904 return ImmutableList.copyOf(portStats.values());
905 }
906
907 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200908 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
909 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
910 if (portStats == null) {
911 return Collections.emptyList();
912 }
913 return ImmutableList.copyOf(portStats.values());
914 }
915
916 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700917 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
918 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
919 return ports == null ? null : ports.get(portNumber);
920 }
921
922 @Override
923 public boolean isAvailable(DeviceId deviceId) {
924 return availableDevices.contains(deviceId);
925 }
926
927 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700928 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800929 final NodeId myId = clusterService.getLocalNode().id();
930 NodeId master = mastershipService.getMasterFor(deviceId);
931
932 // if there exist a master, forward
933 // if there is no master, try to become one and process
934
935 boolean relinquishAtEnd = false;
936 if (master == null) {
937 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
938 if (myRole != MastershipRole.NONE) {
939 relinquishAtEnd = true;
940 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800941 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800942 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800943 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700944 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800945 master = myId;
946 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700947 }
948
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800949 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800950 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700951 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800952
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800953 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700954 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800955 /* error log:
956 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
957 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800958
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800959 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700960 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800961 }
962
963 // I have control..
964
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700965 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700966 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700967 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800968 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700969 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800970 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700971 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800972 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800973 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800974 mastershipService.relinquishMastership(deviceId);
975 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700976 return event;
977 }
978
979 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
980 Timestamp timestamp) {
981
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700982 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700983 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700984 // accept removal request if given timestamp is newer than
985 // the latest Timestamp from Primary provider
986 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
987 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
988 if (timestamp.compareTo(lastTimestamp) <= 0) {
989 // outdated event ignore
990 return null;
991 }
992 removalRequest.put(deviceId, timestamp);
993
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700994 Device device = devices.remove(deviceId);
995 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700996 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
997 if (ports != null) {
998 ports.clear();
999 }
1000 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001001 descs.clear();
1002 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001003 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001004 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001005 }
1006
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001007 /**
1008 * Checks if given timestamp is superseded by removal request
1009 * with more recent timestamp.
1010 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001011 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001012 * @param timestampToCheck timestamp of an event to check
1013 * @return true if device is already removed
1014 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001015 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1016 Timestamp removalTimestamp = removalRequest.get(deviceId);
1017 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001018 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001019 // removalRequest is more recent
1020 return true;
1021 }
1022 return false;
1023 }
1024
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001025 /**
1026 * Returns a Device, merging description given from multiple Providers.
1027 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001028 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001029 * @param providerDescs Collection of Descriptions from multiple providers
1030 * @return Device instance
1031 */
1032 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001033 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001034
Thomas Vachuska444eda62014-10-28 13:09:42 -07001035 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001036
1037 ProviderId primary = pickPrimaryPID(providerDescs);
1038
1039 DeviceDescriptions desc = providerDescs.get(primary);
1040
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001041 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001042 Type type = base.type();
1043 String manufacturer = base.manufacturer();
1044 String hwVersion = base.hwVersion();
1045 String swVersion = base.swVersion();
1046 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001047 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001048 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1049 annotations = merge(annotations, base.annotations());
1050
1051 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1052 if (e.getKey().equals(primary)) {
1053 continue;
1054 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001055 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001056 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001057 // Currently assuming there will never be a key conflict between
1058 // providers
1059
1060 // annotation merging. not so efficient, should revisit later
1061 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1062 }
1063
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001064 return new DefaultDevice(primary, deviceId, type, manufacturer,
1065 hwVersion, swVersion, serialNumber,
1066 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001067 }
1068
Marc De Leenheer88194c32015-05-29 22:10:59 -07001069 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1070 PortDescription description, Annotations annotations) {
1071 switch (description.type()) {
1072 case OMS:
1073 OmsPortDescription omsDesc = (OmsPortDescription) description;
1074 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1075 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1076 case OCH:
1077 OchPortDescription ochDesc = (OchPortDescription) description;
1078 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1079 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1080 case ODUCLT:
1081 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1082 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1083 default:
1084 return new DefaultPort(device, number, isEnabled, description.type(),
1085 description.portSpeed(), annotations);
1086 }
1087 }
1088
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001089 /**
1090 * Returns a Port, merging description given from multiple Providers.
1091 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001092 * @param device device the port is on
1093 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001094 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001095 * @return Port instance
1096 */
1097 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001098 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001099
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001100 ProviderId primary = pickPrimaryPID(descsMap);
1101 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001102 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001103 boolean isEnabled = false;
1104 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001105 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001106 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1107 if (portDesc != null) {
1108 isEnabled = portDesc.value().isEnabled();
1109 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001110 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001111 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001112 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001113 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001114 if (e.getKey().equals(primary)) {
1115 continue;
1116 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001117 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001118 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001119 // Currently assuming there will never be a key conflict between
1120 // providers
1121
1122 // annotation merging. not so efficient, should revisit later
1123 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1124 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001125 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1126 continue;
1127 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001128 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001129 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001130 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001131 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001132 }
1133 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001134 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001135 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001136 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001137 PortDescription current = portDesc.value();
1138 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001139 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001140 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001141 }
1142
1143 /**
1144 * @return primary ProviderID, or randomly chosen one if none exists
1145 */
1146 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001147 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001148 ProviderId fallBackPrimary = null;
1149 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1150 if (!e.getKey().isAncillary()) {
1151 return e.getKey();
1152 } else if (fallBackPrimary == null) {
1153 // pick randomly as a fallback in case there is no primary
1154 fallBackPrimary = e.getKey();
1155 }
1156 }
1157 return fallBackPrimary;
1158 }
1159
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001160 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001161 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001162 ProviderId pid = pickPrimaryPID(providerDescs);
1163 return providerDescs.get(pid);
1164 }
1165
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001166 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001167 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001168 }
1169
Jonathan Hart7d656f42015-01-27 14:07:23 -08001170 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001171 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001172 }
Madan Jampani47c93732014-10-06 20:46:08 -07001173
Jonathan Hart7d656f42015-01-27 14:07:23 -08001174 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001175 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001176 }
1177
Jonathan Hart7d656f42015-01-27 14:07:23 -08001178 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001179 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001180 }
1181
Jonathan Hart7d656f42015-01-27 14:07:23 -08001182 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001183 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001184 }
1185
Jonathan Hart7d656f42015-01-27 14:07:23 -08001186 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001187 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001188 }
1189
Jonathan Hart7d656f42015-01-27 14:07:23 -08001190 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001191 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1192 }
1193
1194 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1195 try {
1196 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1197 } catch (IOException e) {
1198 log.error("Failed to send" + event + " to " + recipient, e);
1199 }
1200 }
1201
1202 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1203 try {
1204 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1205 } catch (IOException e) {
1206 log.error("Failed to send" + event + " to " + recipient, e);
1207 }
1208 }
1209
1210 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1211 try {
1212 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1213 } catch (IOException e) {
1214 log.error("Failed to send" + event + " to " + recipient, e);
1215 }
1216 }
1217
1218 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1219 try {
1220 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1221 } catch (IOException e) {
1222 log.error("Failed to send" + event + " to " + recipient, e);
1223 }
1224 }
1225
1226 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1227 try {
1228 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1229 } catch (IOException e) {
1230 log.error("Failed to send" + event + " to " + recipient, e);
1231 }
1232 }
1233
1234 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1235 final NodeId self = clusterService.getLocalNode().id();
1236
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001237 final int numDevices = deviceDescs.size();
1238 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1239 final int portsPerDevice = 8; // random factor to minimize reallocation
1240 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1241 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001242
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001243 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001244
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001245 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001246 synchronized (devDescs) {
1247
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001248 // send device offline timestamp
1249 Timestamp lOffline = this.offline.get(deviceId);
1250 if (lOffline != null) {
1251 adOffline.put(deviceId, lOffline);
1252 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001253
1254 for (Entry<ProviderId, DeviceDescriptions>
1255 prov : devDescs.entrySet()) {
1256
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001257 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001258 final ProviderId provId = prov.getKey();
1259 final DeviceDescriptions descs = prov.getValue();
1260
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001261 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001262 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001263
1264 for (Entry<PortNumber, Timestamped<PortDescription>>
1265 portDesc : descs.getPortDescs().entrySet()) {
1266
1267 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001268 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001269 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001270 }
1271 }
1272 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001273 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001274
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001275 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001276 }
1277
1278 /**
1279 * Responds to anti-entropy advertisement message.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001280 * <p/>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001281 * Notify sender about out-dated information using regular replication message.
1282 * Send back advertisement to sender if not in sync.
1283 *
1284 * @param advertisement to respond to
1285 */
1286 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1287
1288 final NodeId sender = advertisement.sender();
1289
1290 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1291 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1292 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1293
1294 // Fragments to request
1295 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1296 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1297
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001298 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001299 final DeviceId deviceId = de.getKey();
1300 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1301
1302 synchronized (lDevice) {
1303 // latestTimestamp across provider
1304 // Note: can be null initially
1305 Timestamp localLatest = offline.get(deviceId);
1306
1307 // handle device Ads
1308 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1309 final ProviderId provId = prov.getKey();
1310 final DeviceDescriptions lDeviceDescs = prov.getValue();
1311
1312 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1313
1314
1315 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1316 Timestamp advDevTimestamp = devAds.get(devFragId);
1317
Jonathan Hart403ea932015-02-20 16:23:00 -08001318 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1319 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001320 // remote does not have it or outdated, suggest
1321 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1322 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1323 // local is outdated, request
1324 reqDevices.add(devFragId);
1325 }
1326
1327 // handle port Ads
1328 for (Entry<PortNumber, Timestamped<PortDescription>>
1329 pe : lDeviceDescs.getPortDescs().entrySet()) {
1330
1331 final PortNumber num = pe.getKey();
1332 final Timestamped<PortDescription> lPort = pe.getValue();
1333
1334 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1335
1336 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001337 if (advPortTimestamp == null || lPort.isNewerThan(
1338 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001339 // remote does not have it or outdated, suggest
1340 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1341 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1342 // local is outdated, request
1343 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1344 reqPorts.add(portFragId);
1345 }
1346
1347 // remove port Ad already processed
1348 portAds.remove(portFragId);
1349 } // end local port loop
1350
1351 // remove device Ad already processed
1352 devAds.remove(devFragId);
1353
1354 // find latest and update
1355 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1356 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001357 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001358 localLatest = providerLatest;
1359 }
1360 } // end local provider loop
1361
1362 // checking if remote timestamp is more recent.
1363 Timestamp rOffline = offlineAds.get(deviceId);
1364 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001365 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001366 // remote offline timestamp suggests that the
1367 // device is off-line
1368 markOfflineInternal(deviceId, rOffline);
1369 }
1370
1371 Timestamp lOffline = offline.get(deviceId);
1372 if (lOffline != null && rOffline == null) {
1373 // locally offline, but remote is online, suggest offline
1374 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1375 }
1376
1377 // remove device offline Ad already processed
1378 offlineAds.remove(deviceId);
1379 } // end local device loop
1380 } // device lock
1381
1382 // If there is any Ads left, request them
1383 log.trace("Ads left {}, {}", devAds, portAds);
1384 reqDevices.addAll(devAds.keySet());
1385 reqPorts.addAll(portAds.keySet());
1386
1387 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1388 log.trace("Nothing to request to remote peer {}", sender);
1389 return;
1390 }
1391
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001392 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001393
1394 // 2-way Anti-Entropy for now
1395 try {
1396 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1397 } catch (IOException e) {
1398 log.error("Failed to send response advertisement to " + sender, e);
1399 }
1400
1401// Sketch of 3-way Anti-Entropy
1402// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1403// ClusterMessage message = new ClusterMessage(
1404// clusterService.getLocalNode().id(),
1405// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1406// SERIALIZER.encode(request));
1407//
1408// try {
1409// clusterCommunicator.unicast(message, advertisement.sender());
1410// } catch (IOException e) {
1411// log.error("Failed to send advertisement reply to "
1412// + advertisement.sender(), e);
1413// }
Madan Jampani47c93732014-10-06 20:46:08 -07001414 }
1415
Madan Jampani255a58b2014-10-09 12:08:20 -07001416 private void notifyDelegateIfNotNull(DeviceEvent event) {
1417 if (event != null) {
1418 notifyDelegate(event);
1419 }
1420 }
1421
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001422 private final class SendAdvertisementTask implements Runnable {
1423
1424 @Override
1425 public void run() {
1426 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001427 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001428 return;
1429 }
1430
1431 try {
1432 final NodeId self = clusterService.getLocalNode().id();
1433 Set<ControllerNode> nodes = clusterService.getNodes();
1434
1435 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1436 .transform(toNodeId())
1437 .toList();
1438
1439 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001440 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001441 return;
1442 }
1443
1444 NodeId peer;
1445 do {
1446 int idx = RandomUtils.nextInt(0, nodeIds.size());
1447 peer = nodeIds.get(idx);
1448 } while (peer.equals(self));
1449
1450 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1451
1452 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001453 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001454 return;
1455 }
1456
1457 try {
1458 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1459 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001460 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001461 return;
1462 }
1463 } catch (Exception e) {
1464 // catch all Exception to avoid Scheduled task being suppressed.
1465 log.error("Exception thrown while sending advertisement", e);
1466 }
1467 }
1468 }
1469
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001470 private final class InternalDeviceEventListener
1471 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001472 @Override
1473 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001474 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001475 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001476
Madan Jampani47c93732014-10-06 20:46:08 -07001477 ProviderId providerId = event.providerId();
1478 DeviceId deviceId = event.deviceId();
1479 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001480
Madan Jampani2af244a2015-02-22 13:12:01 -08001481 try {
1482 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1483 } catch (Exception e) {
1484 log.warn("Exception thrown handling device update", e);
1485 }
Madan Jampani47c93732014-10-06 20:46:08 -07001486 }
1487 }
1488
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001489 private final class InternalDeviceOfflineEventListener
1490 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001491 @Override
1492 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001493 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001494 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001495
1496 DeviceId deviceId = event.deviceId();
1497 Timestamp timestamp = event.timestamp();
1498
Madan Jampani2af244a2015-02-22 13:12:01 -08001499 try {
1500 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1501 } catch (Exception e) {
1502 log.warn("Exception thrown handling device offline", e);
1503 }
Madan Jampani25322532014-10-08 11:20:38 -07001504 }
1505 }
1506
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001507 private final class InternalRemoveRequestListener
1508 implements ClusterMessageHandler {
1509 @Override
1510 public void handle(ClusterMessage message) {
1511 log.debug("Received device remove request from peer: {}", message.sender());
1512 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001513
Madan Jampani2af244a2015-02-22 13:12:01 -08001514 try {
1515 removeDevice(did);
1516 } catch (Exception e) {
1517 log.warn("Exception thrown handling device remove", e);
1518 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001519 }
1520 }
1521
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001522 private final class InternalDeviceRemovedEventListener
1523 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001524 @Override
1525 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001526 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001527 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001528
1529 DeviceId deviceId = event.deviceId();
1530 Timestamp timestamp = event.timestamp();
1531
Madan Jampani2af244a2015-02-22 13:12:01 -08001532 try {
1533 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1534 } catch (Exception e) {
1535 log.warn("Exception thrown handling device removed", e);
1536 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001537 }
1538 }
1539
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001540 private final class InternalPortEventListener
1541 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001542 @Override
1543 public void handle(ClusterMessage message) {
1544
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001545 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001546 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001547
1548 ProviderId providerId = event.providerId();
1549 DeviceId deviceId = event.deviceId();
1550 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1551
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001552 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001553 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001554 // Note: dropped information will be recovered by anti-entropy
1555 return;
1556 }
1557
Madan Jampani2af244a2015-02-22 13:12:01 -08001558 try {
1559 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1560 } catch (Exception e) {
1561 log.warn("Exception thrown handling port update", e);
1562 }
Madan Jampani47c93732014-10-06 20:46:08 -07001563 }
1564 }
1565
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001566 private final class InternalPortStatusEventListener
1567 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001568 @Override
1569 public void handle(ClusterMessage message) {
1570
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001571 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001572 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001573
1574 ProviderId providerId = event.providerId();
1575 DeviceId deviceId = event.deviceId();
1576 Timestamped<PortDescription> portDescription = event.portDescription();
1577
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001578 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001579 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001580 // Note: dropped information will be recovered by anti-entropy
1581 return;
1582 }
1583
Madan Jampani2af244a2015-02-22 13:12:01 -08001584 try {
1585 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1586 } catch (Exception e) {
1587 log.warn("Exception thrown handling port update", e);
1588 }
Madan Jampani47c93732014-10-06 20:46:08 -07001589 }
1590 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001591
1592 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001593 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001594 @Override
1595 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001596 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001597 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001598 try {
1599 handleAdvertisement(advertisement);
1600 } catch (Exception e) {
1601 log.warn("Exception thrown handling Device advertisements.", e);
1602 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001603 }
1604 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001605
1606 private final class DeviceInjectedEventListener
1607 implements ClusterMessageHandler {
1608 @Override
1609 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001610 log.debug("Received injected device event from peer: {}", message.sender());
1611 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1612
1613 ProviderId providerId = event.providerId();
1614 DeviceId deviceId = event.deviceId();
1615 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001616 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1617 // workaround for ONOS-1208
1618 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1619 return;
1620 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001621
Madan Jampani2af244a2015-02-22 13:12:01 -08001622 try {
1623 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1624 } catch (Exception e) {
1625 log.warn("Exception thrown handling device injected event.", e);
1626 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001627 }
1628 }
1629
1630 private final class PortInjectedEventListener
1631 implements ClusterMessageHandler {
1632 @Override
1633 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001634 log.debug("Received injected port event from peer: {}", message.sender());
1635 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1636
1637 ProviderId providerId = event.providerId();
1638 DeviceId deviceId = event.deviceId();
1639 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001640 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1641 // workaround for ONOS-1208
1642 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1643 return;
1644 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001645
Madan Jampani2af244a2015-02-22 13:12:01 -08001646 try {
1647 updatePorts(providerId, deviceId, portDescriptions);
1648 } catch (Exception e) {
1649 log.warn("Exception thrown handling port injected event.", e);
1650 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001651 }
1652 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001653
1654 private class InternalPortStatsListener
1655 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1656 @Override
1657 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1658 if (event.type() == PUT) {
1659 Device device = devices.get(event.key());
1660 if (device != null) {
1661 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1662 }
1663 }
1664 }
1665 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001666}