blob: 85e67decf82ea176cf457f9939f386a88f4055f2 [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.
alshabibdc5d8bd2015-11-02 15:41:29 -0800430 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700431 if ((providerId.isAncillary() && annotationsChanged) ||
432 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700433 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
434 if (!replaced) {
435 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700436 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
437 providerId, oldDevice, devices.get(newDevice.id())
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700438 , newDevice);
439 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700440
alshabibdc5d8bd2015-11-02 15:41:29 -0800441 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700442 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800443
444 if (!providerId.isAncillary()) {
445 boolean wasOnline = availableDevices.contains(newDevice.id());
446 markOnline(newDevice.id(), newTimestamp);
447 if (!wasOnline) {
448 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
449 }
450 }
451 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700452 }
453
454 @Override
455 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700456 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700457 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700458 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700459 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700460 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800461 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700462 }
463 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700464 }
465
466 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
467
468 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700469 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700470
471 // locking device
472 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700473
474 // accept off-line if given timestamp is newer than
475 // the latest Timestamp from Primary provider
476 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
477 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
478 if (timestamp.compareTo(lastTimestamp) <= 0) {
479 // outdated event ignore
480 return null;
481 }
482
483 offline.put(deviceId, timestamp);
484
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700485 Device device = devices.get(deviceId);
486 if (device == null) {
487 return null;
488 }
489 boolean removed = availableDevices.remove(deviceId);
490 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700491 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700492 }
493 return null;
494 }
495 }
496
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700497 /**
498 * Marks the device as available if the given timestamp is not outdated,
499 * compared to the time the device has been marked offline.
500 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700501 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700502 * @param timestamp of the event triggering this change.
503 * @return true if availability change request was accepted and changed the state
504 */
505 // Guarded by deviceDescs value (=Device lock)
506 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
507 // accept on-line if given timestamp is newer than
508 // the latest offline request Timestamp
509 Timestamp offlineTimestamp = offline.get(deviceId);
510 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700511 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700512
513 offline.remove(deviceId);
514 return availableDevices.add(deviceId);
515 }
516 return false;
517 }
518
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700519 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700520 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700521 DeviceId deviceId,
522 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700523
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800524 NodeId localNode = clusterService.getLocalNode().id();
525 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
526 // since it will trigger distributed store read.
527 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
528 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
529 // If we don't care much about topology performance, then it might be OK.
530 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700531
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800532 // Process port update only if we're the master of the device,
533 // otherwise signal the actual master.
534 List<DeviceEvent> deviceEvents = null;
535 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700536
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800537 final Timestamp newTimestamp;
538 try {
539 newTimestamp = deviceClockService.getTimestamp(deviceId);
540 } catch (IllegalStateException e) {
541 log.info("Timestamp was not available for device {}", deviceId);
542 log.debug(" discarding {}", portDescriptions);
543 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700544
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800545 // Possible situation:
546 // Device connected and became master for short period of time,
547 // but lost mastership before this instance had the chance to
548 // retrieve term information.
549
550 // Information dropped here is expected to be recoverable by
551 // device probing after mastership change
552
553 return Collections.emptyList();
554 }
555 log.debug("timestamp for {} {}", deviceId, newTimestamp);
556
557 final Timestamped<List<PortDescription>> timestampedInput
558 = new Timestamped<>(portDescriptions, newTimestamp);
559 final Timestamped<List<PortDescription>> merged;
560
561 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
562
563 synchronized (device) {
564 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
565 final DeviceDescriptions descs = device.get(providerId);
566 List<PortDescription> mergedList =
567 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700568 .transform(input ->
569 // lookup merged port description
570 descs.getPortDesc(input.portNumber()).value()
571 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700572 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800573 }
574
575 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700576 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700577 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800578 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
579 }
580
581 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800582 // FIXME Temporary hack for NPE (ONOS-1171).
583 // Proper fix is to implement forwarding to master on ConfigProvider
584 // redo ONOS-490
585 if (deviceNode == null) {
586 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800587 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800588 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800589
590 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800591
592 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700593 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800594 /* error log:
595 log.warn("Failed to process injected ports of device id: {} " +
596 "(cluster messaging failed: {})",
597 deviceId, e);
598 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700599 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700600
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800601 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700602 }
603
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700604 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700605 DeviceId deviceId,
606 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700607
608 Device device = devices.get(deviceId);
609 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
610
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700611 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700612 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
613
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700614 List<DeviceEvent> events = new ArrayList<>();
615 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700616
617 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
618 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700619 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700620 }
621
622 DeviceDescriptions descs = descsMap.get(providerId);
623 // every provider must provide DeviceDescription.
624 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700625 "Device description for Device ID %s from Provider %s was not found",
626 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700627
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700628 Map<PortNumber, Port> ports = getPortMap(deviceId);
629
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700630 final Timestamp newTimestamp = portDescriptions.timestamp();
631
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700632 // Add new ports
633 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700634 for (PortDescription portDescription : portDescriptions.value()) {
635 final PortNumber number = portDescription.portNumber();
636 processed.add(number);
637
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700638 final Port oldPort = ports.get(number);
639 final Port newPort;
640
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700641
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700642 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
643 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700644 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700645 // on new port or valid update
646 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700647 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700648 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700649 newPort = composePort(device, number, descsMap);
650 } else {
651 // outdated event, ignored.
652 continue;
653 }
654
655 events.add(oldPort == null ?
656 createPort(device, newPort, ports) :
657 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700658 }
659
660 events.addAll(pruneOldPorts(device, ports, processed));
661 }
662 return FluentIterable.from(events).filter(notNull()).toList();
663 }
664
665 // Creates a new port based on the port description adds it to the map and
666 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700667 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700668 private DeviceEvent createPort(Device device, Port newPort,
669 Map<PortNumber, Port> ports) {
670 ports.put(newPort.number(), newPort);
671 return new DeviceEvent(PORT_ADDED, device, newPort);
672 }
673
674 // Checks if the specified port requires update and if so, it replaces the
675 // existing entry in the map and 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 updatePort(Device device, Port oldPort,
678 Port newPort,
679 Map<PortNumber, Port> ports) {
680 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700681 oldPort.type() != newPort.type() ||
682 oldPort.portSpeed() != newPort.portSpeed() ||
683 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700684 ports.put(oldPort.number(), newPort);
685 return new DeviceEvent(PORT_UPDATED, device, newPort);
686 }
687 return null;
688 }
689
690 // Prunes the specified list of ports based on which ports are in the
691 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700692 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700693 private List<DeviceEvent> pruneOldPorts(Device device,
694 Map<PortNumber, Port> ports,
695 Set<PortNumber> processed) {
696 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700697 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700698 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700699 Entry<PortNumber, Port> e = iterator.next();
700 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700701 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700702 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700703 iterator.remove();
704 }
705 }
706 return events;
707 }
708
709 // Gets the map of ports for the specified device; if one does not already
710 // exist, it creates and registers a new one.
711 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
712 return createIfAbsentUnchecked(devicePorts, deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700713 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700714 }
715
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700716 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700717 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700718 Map<ProviderId, DeviceDescriptions> r;
719 r = deviceDescs.get(deviceId);
720 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700721 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700722 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
723 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
724 if (concurrentlyAdded != null) {
725 r = concurrentlyAdded;
726 }
727 }
728 return r;
729 }
730
731 // Guarded by deviceDescs value (=Device lock)
732 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
733 Map<ProviderId, DeviceDescriptions> device,
734 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700735 synchronized (device) {
736 DeviceDescriptions r = device.get(providerId);
737 if (r == null) {
738 r = new DeviceDescriptions(deltaDesc);
739 device.put(providerId, r);
740 }
741 return r;
742 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700743 }
744
745 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700746 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
747 DeviceId deviceId,
748 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700749 final Timestamp newTimestamp;
750 try {
751 newTimestamp = deviceClockService.getTimestamp(deviceId);
752 } catch (IllegalStateException e) {
753 log.info("Timestamp was not available for device {}", deviceId);
754 log.debug(" discarding {}", portDescription);
755 // Failed to generate timestamp. Ignoring.
756 // See updatePorts comment
757 return null;
758 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700759 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700760 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700761 final DeviceEvent event;
762 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800763 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
764 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700765 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800766 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700767 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700768 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700769 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700770 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700771 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800772 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700773 }
774 return event;
775 }
776
777 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700778 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700779 Device device = devices.get(deviceId);
780 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
781
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700782 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700783 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
784
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700785 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700786
787 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
788 log.debug("Ignoring outdated event: {}", deltaDesc);
789 return null;
790 }
791
792 DeviceDescriptions descs = descsMap.get(providerId);
793 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700794 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700795 "Device description for Device ID %s from Provider %s was not found",
796 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700797
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700798 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
799 final PortNumber number = deltaDesc.value().portNumber();
800 final Port oldPort = ports.get(number);
801 final Port newPort;
802
803 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
804 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700805 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700806 // on new port or valid update
807 // update description
808 descs.putPortDesc(deltaDesc);
809 newPort = composePort(device, number, descsMap);
810 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700811 // same or outdated event, ignored.
812 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700813 return null;
814 }
815
816 if (oldPort == null) {
817 return createPort(device, newPort, ports);
818 } else {
819 return updatePort(device, oldPort, newPort, ports);
820 }
821 }
822 }
823
824 @Override
825 public List<Port> getPorts(DeviceId deviceId) {
826 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
827 if (ports == null) {
828 return Collections.emptyList();
829 }
830 return ImmutableList.copyOf(ports.values());
831 }
832
833 @Override
sangho538108b2015-04-08 14:29:20 -0700834 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200835 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700836
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200837 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
838 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
839 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
840
841 if (prvStatsMap != null) {
842 for (PortStatistics newStats : newStatsCollection) {
843 PortNumber port = PortNumber.portNumber(newStats.port());
844 PortStatistics prvStats = prvStatsMap.get(port);
845 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
846 PortStatistics deltaStats = builder.build();
847 if (prvStats != null) {
848 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
849 }
850 deltaStatsMap.put(port, deltaStats);
851 newStatsMap.put(port, newStats);
852 }
853 } else {
854 for (PortStatistics newStats : newStatsCollection) {
855 PortNumber port = PortNumber.portNumber(newStats.port());
856 newStatsMap.put(port, newStats);
857 }
sangho538108b2015-04-08 14:29:20 -0700858 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200859 devicePortDeltaStats.put(deviceId, deltaStatsMap);
860 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200861 // DeviceEvent returns null because of InternalPortStatsListener usage
862 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200863 }
864
865 /**
866 * Calculate delta statistics by subtracting previous from new statistics.
867 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700868 * @param deviceId device identifier
869 * @param prvStats previous port statistics
870 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200871 * @return PortStatistics
872 */
873 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
874 // calculate time difference
875 long deltaStatsSec, deltaStatsNano;
876 if (newStats.durationNano() < prvStats.durationNano()) {
877 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
878 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
879 } else {
880 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
881 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
882 }
883 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
884 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
885 .setPort(newStats.port())
886 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
887 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
888 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
889 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
890 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
891 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
892 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
893 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
894 .setDurationSec(deltaStatsSec)
895 .setDurationNano(deltaStatsNano)
896 .build();
897 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700898 }
899
900 @Override
901 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700902 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
903 if (portStats == null) {
904 return Collections.emptyList();
905 }
906 return ImmutableList.copyOf(portStats.values());
907 }
908
909 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200910 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
911 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
912 if (portStats == null) {
913 return Collections.emptyList();
914 }
915 return ImmutableList.copyOf(portStats.values());
916 }
917
918 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700919 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
920 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
921 return ports == null ? null : ports.get(portNumber);
922 }
923
924 @Override
925 public boolean isAvailable(DeviceId deviceId) {
926 return availableDevices.contains(deviceId);
927 }
928
929 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700930 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800931 final NodeId myId = clusterService.getLocalNode().id();
932 NodeId master = mastershipService.getMasterFor(deviceId);
933
934 // if there exist a master, forward
935 // if there is no master, try to become one and process
936
937 boolean relinquishAtEnd = false;
938 if (master == null) {
939 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
940 if (myRole != MastershipRole.NONE) {
941 relinquishAtEnd = true;
942 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800943 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800944 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800945 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700946 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800947 master = myId;
948 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700949 }
950
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800951 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800952 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700953 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800954
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800955 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700956 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800957 /* error log:
958 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
959 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800960
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800961 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700962 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800963 }
964
965 // I have control..
966
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700967 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700968 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700969 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800970 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700971 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800972 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700973 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800974 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800975 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800976 mastershipService.relinquishMastership(deviceId);
977 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700978 return event;
979 }
980
981 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
982 Timestamp timestamp) {
983
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700984 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700985 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700986 // accept removal request if given timestamp is newer than
987 // the latest Timestamp from Primary provider
988 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -0800989 if (primDescs == null) {
990 return null;
991 }
992
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700993 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
994 if (timestamp.compareTo(lastTimestamp) <= 0) {
995 // outdated event ignore
996 return null;
997 }
998 removalRequest.put(deviceId, timestamp);
999
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001000 Device device = devices.remove(deviceId);
1001 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001002 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1003 if (ports != null) {
1004 ports.clear();
1005 }
1006 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001007 descs.clear();
1008 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001009 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001010 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001011 }
1012
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001013 /**
1014 * Checks if given timestamp is superseded by removal request
1015 * with more recent timestamp.
1016 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001017 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001018 * @param timestampToCheck timestamp of an event to check
1019 * @return true if device is already removed
1020 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001021 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1022 Timestamp removalTimestamp = removalRequest.get(deviceId);
1023 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001024 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001025 // removalRequest is more recent
1026 return true;
1027 }
1028 return false;
1029 }
1030
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001031 /**
1032 * Returns a Device, merging description given from multiple Providers.
1033 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001034 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001035 * @param providerDescs Collection of Descriptions from multiple providers
1036 * @return Device instance
1037 */
1038 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001039 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001040
Thomas Vachuska444eda62014-10-28 13:09:42 -07001041 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001042
1043 ProviderId primary = pickPrimaryPID(providerDescs);
1044
1045 DeviceDescriptions desc = providerDescs.get(primary);
1046
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001047 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001048 Type type = base.type();
1049 String manufacturer = base.manufacturer();
1050 String hwVersion = base.hwVersion();
1051 String swVersion = base.swVersion();
1052 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001053 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001054 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1055 annotations = merge(annotations, base.annotations());
1056
1057 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1058 if (e.getKey().equals(primary)) {
1059 continue;
1060 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001061 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001062 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001063 // Currently assuming there will never be a key conflict between
1064 // providers
1065
1066 // annotation merging. not so efficient, should revisit later
1067 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1068 }
1069
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001070 return new DefaultDevice(primary, deviceId, type, manufacturer,
1071 hwVersion, swVersion, serialNumber,
1072 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001073 }
1074
Marc De Leenheer88194c32015-05-29 22:10:59 -07001075 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1076 PortDescription description, Annotations annotations) {
1077 switch (description.type()) {
1078 case OMS:
1079 OmsPortDescription omsDesc = (OmsPortDescription) description;
1080 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1081 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1082 case OCH:
1083 OchPortDescription ochDesc = (OchPortDescription) description;
1084 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1085 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1086 case ODUCLT:
1087 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1088 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1089 default:
1090 return new DefaultPort(device, number, isEnabled, description.type(),
1091 description.portSpeed(), annotations);
1092 }
1093 }
1094
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001095 /**
1096 * Returns a Port, merging description given from multiple Providers.
1097 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001098 * @param device device the port is on
1099 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001100 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001101 * @return Port instance
1102 */
1103 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001104 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001105
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001106 ProviderId primary = pickPrimaryPID(descsMap);
1107 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001108 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001109 boolean isEnabled = false;
1110 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001111 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001112 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1113 if (portDesc != null) {
1114 isEnabled = portDesc.value().isEnabled();
1115 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001116 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001117 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001118 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001119 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001120 if (e.getKey().equals(primary)) {
1121 continue;
1122 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001123 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001124 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001125 // Currently assuming there will never be a key conflict between
1126 // providers
1127
1128 // annotation merging. not so efficient, should revisit later
1129 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1130 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001131 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1132 continue;
1133 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001134 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001135 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001136 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001137 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001138 }
1139 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001140 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001141 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001142 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001143 PortDescription current = portDesc.value();
1144 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001145 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001146 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001147 }
1148
1149 /**
1150 * @return primary ProviderID, or randomly chosen one if none exists
1151 */
1152 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001153 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001154 ProviderId fallBackPrimary = null;
1155 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1156 if (!e.getKey().isAncillary()) {
1157 return e.getKey();
1158 } else if (fallBackPrimary == null) {
1159 // pick randomly as a fallback in case there is no primary
1160 fallBackPrimary = e.getKey();
1161 }
1162 }
1163 return fallBackPrimary;
1164 }
1165
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001166 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001167 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001168 ProviderId pid = pickPrimaryPID(providerDescs);
1169 return providerDescs.get(pid);
1170 }
1171
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001172 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001173 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001174 }
1175
Jonathan Hart7d656f42015-01-27 14:07:23 -08001176 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001177 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001178 }
Madan Jampani47c93732014-10-06 20:46:08 -07001179
Jonathan Hart7d656f42015-01-27 14:07:23 -08001180 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001181 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001182 }
1183
Jonathan Hart7d656f42015-01-27 14:07:23 -08001184 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001185 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001186 }
1187
Jonathan Hart7d656f42015-01-27 14:07:23 -08001188 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001189 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001190 }
1191
Jonathan Hart7d656f42015-01-27 14:07:23 -08001192 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001193 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001194 }
1195
Jonathan Hart7d656f42015-01-27 14:07:23 -08001196 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001197 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1198 }
1199
1200 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1201 try {
1202 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1203 } catch (IOException e) {
1204 log.error("Failed to send" + event + " to " + recipient, e);
1205 }
1206 }
1207
1208 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1209 try {
1210 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1211 } catch (IOException e) {
1212 log.error("Failed to send" + event + " to " + recipient, e);
1213 }
1214 }
1215
1216 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1217 try {
1218 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1219 } catch (IOException e) {
1220 log.error("Failed to send" + event + " to " + recipient, e);
1221 }
1222 }
1223
1224 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1225 try {
1226 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1227 } catch (IOException e) {
1228 log.error("Failed to send" + event + " to " + recipient, e);
1229 }
1230 }
1231
1232 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1233 try {
1234 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1235 } catch (IOException e) {
1236 log.error("Failed to send" + event + " to " + recipient, e);
1237 }
1238 }
1239
1240 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1241 final NodeId self = clusterService.getLocalNode().id();
1242
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001243 final int numDevices = deviceDescs.size();
1244 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1245 final int portsPerDevice = 8; // random factor to minimize reallocation
1246 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1247 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001248
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001249 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001250
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001251 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001252 synchronized (devDescs) {
1253
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001254 // send device offline timestamp
1255 Timestamp lOffline = this.offline.get(deviceId);
1256 if (lOffline != null) {
1257 adOffline.put(deviceId, lOffline);
1258 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001259
1260 for (Entry<ProviderId, DeviceDescriptions>
1261 prov : devDescs.entrySet()) {
1262
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001263 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001264 final ProviderId provId = prov.getKey();
1265 final DeviceDescriptions descs = prov.getValue();
1266
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001267 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001268 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001269
1270 for (Entry<PortNumber, Timestamped<PortDescription>>
1271 portDesc : descs.getPortDescs().entrySet()) {
1272
1273 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001274 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001275 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001276 }
1277 }
1278 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001279 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001280
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001281 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001282 }
1283
1284 /**
1285 * Responds to anti-entropy advertisement message.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001286 * <p/>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001287 * Notify sender about out-dated information using regular replication message.
1288 * Send back advertisement to sender if not in sync.
1289 *
1290 * @param advertisement to respond to
1291 */
1292 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1293
1294 final NodeId sender = advertisement.sender();
1295
1296 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1297 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1298 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1299
1300 // Fragments to request
1301 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1302 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1303
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001304 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001305 final DeviceId deviceId = de.getKey();
1306 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1307
1308 synchronized (lDevice) {
1309 // latestTimestamp across provider
1310 // Note: can be null initially
1311 Timestamp localLatest = offline.get(deviceId);
1312
1313 // handle device Ads
1314 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1315 final ProviderId provId = prov.getKey();
1316 final DeviceDescriptions lDeviceDescs = prov.getValue();
1317
1318 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1319
1320
1321 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1322 Timestamp advDevTimestamp = devAds.get(devFragId);
1323
Jonathan Hart403ea932015-02-20 16:23:00 -08001324 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1325 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001326 // remote does not have it or outdated, suggest
1327 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1328 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1329 // local is outdated, request
1330 reqDevices.add(devFragId);
1331 }
1332
1333 // handle port Ads
1334 for (Entry<PortNumber, Timestamped<PortDescription>>
1335 pe : lDeviceDescs.getPortDescs().entrySet()) {
1336
1337 final PortNumber num = pe.getKey();
1338 final Timestamped<PortDescription> lPort = pe.getValue();
1339
1340 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1341
1342 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001343 if (advPortTimestamp == null || lPort.isNewerThan(
1344 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001345 // remote does not have it or outdated, suggest
1346 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1347 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1348 // local is outdated, request
1349 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1350 reqPorts.add(portFragId);
1351 }
1352
1353 // remove port Ad already processed
1354 portAds.remove(portFragId);
1355 } // end local port loop
1356
1357 // remove device Ad already processed
1358 devAds.remove(devFragId);
1359
1360 // find latest and update
1361 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1362 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001363 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001364 localLatest = providerLatest;
1365 }
1366 } // end local provider loop
1367
1368 // checking if remote timestamp is more recent.
1369 Timestamp rOffline = offlineAds.get(deviceId);
1370 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001371 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001372 // remote offline timestamp suggests that the
1373 // device is off-line
1374 markOfflineInternal(deviceId, rOffline);
1375 }
1376
1377 Timestamp lOffline = offline.get(deviceId);
1378 if (lOffline != null && rOffline == null) {
1379 // locally offline, but remote is online, suggest offline
1380 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1381 }
1382
1383 // remove device offline Ad already processed
1384 offlineAds.remove(deviceId);
1385 } // end local device loop
1386 } // device lock
1387
1388 // If there is any Ads left, request them
1389 log.trace("Ads left {}, {}", devAds, portAds);
1390 reqDevices.addAll(devAds.keySet());
1391 reqPorts.addAll(portAds.keySet());
1392
1393 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1394 log.trace("Nothing to request to remote peer {}", sender);
1395 return;
1396 }
1397
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001398 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001399
1400 // 2-way Anti-Entropy for now
1401 try {
1402 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1403 } catch (IOException e) {
1404 log.error("Failed to send response advertisement to " + sender, e);
1405 }
1406
1407// Sketch of 3-way Anti-Entropy
1408// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1409// ClusterMessage message = new ClusterMessage(
1410// clusterService.getLocalNode().id(),
1411// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1412// SERIALIZER.encode(request));
1413//
1414// try {
1415// clusterCommunicator.unicast(message, advertisement.sender());
1416// } catch (IOException e) {
1417// log.error("Failed to send advertisement reply to "
1418// + advertisement.sender(), e);
1419// }
Madan Jampani47c93732014-10-06 20:46:08 -07001420 }
1421
Madan Jampani255a58b2014-10-09 12:08:20 -07001422 private void notifyDelegateIfNotNull(DeviceEvent event) {
1423 if (event != null) {
1424 notifyDelegate(event);
1425 }
1426 }
1427
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001428 private final class SendAdvertisementTask implements Runnable {
1429
1430 @Override
1431 public void run() {
1432 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001433 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001434 return;
1435 }
1436
1437 try {
1438 final NodeId self = clusterService.getLocalNode().id();
1439 Set<ControllerNode> nodes = clusterService.getNodes();
1440
1441 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1442 .transform(toNodeId())
1443 .toList();
1444
1445 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001446 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001447 return;
1448 }
1449
1450 NodeId peer;
1451 do {
1452 int idx = RandomUtils.nextInt(0, nodeIds.size());
1453 peer = nodeIds.get(idx);
1454 } while (peer.equals(self));
1455
1456 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1457
1458 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001459 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001460 return;
1461 }
1462
1463 try {
1464 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1465 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001466 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001467 return;
1468 }
1469 } catch (Exception e) {
1470 // catch all Exception to avoid Scheduled task being suppressed.
1471 log.error("Exception thrown while sending advertisement", e);
1472 }
1473 }
1474 }
1475
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001476 private final class InternalDeviceEventListener
1477 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001478 @Override
1479 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001480 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001481 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001482
Madan Jampani47c93732014-10-06 20:46:08 -07001483 ProviderId providerId = event.providerId();
1484 DeviceId deviceId = event.deviceId();
1485 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001486
Madan Jampani2af244a2015-02-22 13:12:01 -08001487 try {
1488 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1489 } catch (Exception e) {
1490 log.warn("Exception thrown handling device update", e);
1491 }
Madan Jampani47c93732014-10-06 20:46:08 -07001492 }
1493 }
1494
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001495 private final class InternalDeviceOfflineEventListener
1496 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001497 @Override
1498 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001499 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001500 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001501
1502 DeviceId deviceId = event.deviceId();
1503 Timestamp timestamp = event.timestamp();
1504
Madan Jampani2af244a2015-02-22 13:12:01 -08001505 try {
1506 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1507 } catch (Exception e) {
1508 log.warn("Exception thrown handling device offline", e);
1509 }
Madan Jampani25322532014-10-08 11:20:38 -07001510 }
1511 }
1512
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001513 private final class InternalRemoveRequestListener
1514 implements ClusterMessageHandler {
1515 @Override
1516 public void handle(ClusterMessage message) {
1517 log.debug("Received device remove request from peer: {}", message.sender());
1518 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001519
Madan Jampani2af244a2015-02-22 13:12:01 -08001520 try {
1521 removeDevice(did);
1522 } catch (Exception e) {
1523 log.warn("Exception thrown handling device remove", e);
1524 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001525 }
1526 }
1527
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001528 private final class InternalDeviceRemovedEventListener
1529 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001530 @Override
1531 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001532 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001533 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001534
1535 DeviceId deviceId = event.deviceId();
1536 Timestamp timestamp = event.timestamp();
1537
Madan Jampani2af244a2015-02-22 13:12:01 -08001538 try {
1539 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1540 } catch (Exception e) {
1541 log.warn("Exception thrown handling device removed", e);
1542 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001543 }
1544 }
1545
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001546 private final class InternalPortEventListener
1547 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001548 @Override
1549 public void handle(ClusterMessage message) {
1550
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001551 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001552 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001553
1554 ProviderId providerId = event.providerId();
1555 DeviceId deviceId = event.deviceId();
1556 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1557
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001558 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001559 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001560 // Note: dropped information will be recovered by anti-entropy
1561 return;
1562 }
1563
Madan Jampani2af244a2015-02-22 13:12:01 -08001564 try {
1565 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1566 } catch (Exception e) {
1567 log.warn("Exception thrown handling port update", e);
1568 }
Madan Jampani47c93732014-10-06 20:46:08 -07001569 }
1570 }
1571
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001572 private final class InternalPortStatusEventListener
1573 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001574 @Override
1575 public void handle(ClusterMessage message) {
1576
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001577 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001578 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001579
1580 ProviderId providerId = event.providerId();
1581 DeviceId deviceId = event.deviceId();
1582 Timestamped<PortDescription> portDescription = event.portDescription();
1583
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001584 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001585 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001586 // Note: dropped information will be recovered by anti-entropy
1587 return;
1588 }
1589
Madan Jampani2af244a2015-02-22 13:12:01 -08001590 try {
1591 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1592 } catch (Exception e) {
1593 log.warn("Exception thrown handling port update", e);
1594 }
Madan Jampani47c93732014-10-06 20:46:08 -07001595 }
1596 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001597
1598 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001599 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001600 @Override
1601 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001602 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001603 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001604 try {
1605 handleAdvertisement(advertisement);
1606 } catch (Exception e) {
1607 log.warn("Exception thrown handling Device advertisements.", e);
1608 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001609 }
1610 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001611
1612 private final class DeviceInjectedEventListener
1613 implements ClusterMessageHandler {
1614 @Override
1615 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001616 log.debug("Received injected device event from peer: {}", message.sender());
1617 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1618
1619 ProviderId providerId = event.providerId();
1620 DeviceId deviceId = event.deviceId();
1621 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001622 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1623 // workaround for ONOS-1208
1624 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1625 return;
1626 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001627
Madan Jampani2af244a2015-02-22 13:12:01 -08001628 try {
1629 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1630 } catch (Exception e) {
1631 log.warn("Exception thrown handling device injected event.", e);
1632 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001633 }
1634 }
1635
1636 private final class PortInjectedEventListener
1637 implements ClusterMessageHandler {
1638 @Override
1639 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001640 log.debug("Received injected port event from peer: {}", message.sender());
1641 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1642
1643 ProviderId providerId = event.providerId();
1644 DeviceId deviceId = event.deviceId();
1645 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001646 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1647 // workaround for ONOS-1208
1648 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1649 return;
1650 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001651
Madan Jampani2af244a2015-02-22 13:12:01 -08001652 try {
1653 updatePorts(providerId, deviceId, portDescriptions);
1654 } catch (Exception e) {
1655 log.warn("Exception thrown handling port injected event.", e);
1656 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001657 }
1658 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001659
1660 private class InternalPortStatsListener
1661 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1662 @Override
1663 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1664 if (event.type() == PUT) {
1665 Device device = devices.get(event.key());
1666 if (device != null) {
1667 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1668 }
1669 }
1670 }
1671 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001672}