blob: 687762e050782f748bed18aa99620114ec151bb1 [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);
989 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
990 if (timestamp.compareTo(lastTimestamp) <= 0) {
991 // outdated event ignore
992 return null;
993 }
994 removalRequest.put(deviceId, timestamp);
995
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700996 Device device = devices.remove(deviceId);
997 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700998 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
999 if (ports != null) {
1000 ports.clear();
1001 }
1002 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001003 descs.clear();
1004 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001005 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001006 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001007 }
1008
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001009 /**
1010 * Checks if given timestamp is superseded by removal request
1011 * with more recent timestamp.
1012 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001013 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001014 * @param timestampToCheck timestamp of an event to check
1015 * @return true if device is already removed
1016 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001017 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1018 Timestamp removalTimestamp = removalRequest.get(deviceId);
1019 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001020 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001021 // removalRequest is more recent
1022 return true;
1023 }
1024 return false;
1025 }
1026
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001027 /**
1028 * Returns a Device, merging description given from multiple Providers.
1029 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001030 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001031 * @param providerDescs Collection of Descriptions from multiple providers
1032 * @return Device instance
1033 */
1034 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001035 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001036
Thomas Vachuska444eda62014-10-28 13:09:42 -07001037 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001038
1039 ProviderId primary = pickPrimaryPID(providerDescs);
1040
1041 DeviceDescriptions desc = providerDescs.get(primary);
1042
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001043 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001044 Type type = base.type();
1045 String manufacturer = base.manufacturer();
1046 String hwVersion = base.hwVersion();
1047 String swVersion = base.swVersion();
1048 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001049 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001050 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1051 annotations = merge(annotations, base.annotations());
1052
1053 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1054 if (e.getKey().equals(primary)) {
1055 continue;
1056 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001057 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001058 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001059 // Currently assuming there will never be a key conflict between
1060 // providers
1061
1062 // annotation merging. not so efficient, should revisit later
1063 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1064 }
1065
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001066 return new DefaultDevice(primary, deviceId, type, manufacturer,
1067 hwVersion, swVersion, serialNumber,
1068 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001069 }
1070
Marc De Leenheer88194c32015-05-29 22:10:59 -07001071 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1072 PortDescription description, Annotations annotations) {
1073 switch (description.type()) {
1074 case OMS:
1075 OmsPortDescription omsDesc = (OmsPortDescription) description;
1076 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1077 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1078 case OCH:
1079 OchPortDescription ochDesc = (OchPortDescription) description;
1080 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1081 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1082 case ODUCLT:
1083 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1084 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1085 default:
1086 return new DefaultPort(device, number, isEnabled, description.type(),
1087 description.portSpeed(), annotations);
1088 }
1089 }
1090
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001091 /**
1092 * Returns a Port, merging description given from multiple Providers.
1093 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001094 * @param device device the port is on
1095 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001096 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001097 * @return Port instance
1098 */
1099 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001100 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001101
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001102 ProviderId primary = pickPrimaryPID(descsMap);
1103 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001104 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001105 boolean isEnabled = false;
1106 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001107 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001108 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1109 if (portDesc != null) {
1110 isEnabled = portDesc.value().isEnabled();
1111 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001112 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001113 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001114 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001115 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001116 if (e.getKey().equals(primary)) {
1117 continue;
1118 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001119 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001120 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001121 // Currently assuming there will never be a key conflict between
1122 // providers
1123
1124 // annotation merging. not so efficient, should revisit later
1125 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1126 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001127 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1128 continue;
1129 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001130 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001131 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001132 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001133 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001134 }
1135 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001136 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001137 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001138 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001139 PortDescription current = portDesc.value();
1140 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001141 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001142 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001143 }
1144
1145 /**
1146 * @return primary ProviderID, or randomly chosen one if none exists
1147 */
1148 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001149 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001150 ProviderId fallBackPrimary = null;
1151 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1152 if (!e.getKey().isAncillary()) {
1153 return e.getKey();
1154 } else if (fallBackPrimary == null) {
1155 // pick randomly as a fallback in case there is no primary
1156 fallBackPrimary = e.getKey();
1157 }
1158 }
1159 return fallBackPrimary;
1160 }
1161
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001162 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001163 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001164 ProviderId pid = pickPrimaryPID(providerDescs);
1165 return providerDescs.get(pid);
1166 }
1167
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001168 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001169 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001170 }
1171
Jonathan Hart7d656f42015-01-27 14:07:23 -08001172 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001173 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001174 }
Madan Jampani47c93732014-10-06 20:46:08 -07001175
Jonathan Hart7d656f42015-01-27 14:07:23 -08001176 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001177 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001178 }
1179
Jonathan Hart7d656f42015-01-27 14:07:23 -08001180 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001181 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001182 }
1183
Jonathan Hart7d656f42015-01-27 14:07:23 -08001184 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001185 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001186 }
1187
Jonathan Hart7d656f42015-01-27 14:07:23 -08001188 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001189 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001190 }
1191
Jonathan Hart7d656f42015-01-27 14:07:23 -08001192 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001193 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1194 }
1195
1196 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1197 try {
1198 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1199 } catch (IOException e) {
1200 log.error("Failed to send" + event + " to " + recipient, e);
1201 }
1202 }
1203
1204 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1205 try {
1206 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1207 } catch (IOException e) {
1208 log.error("Failed to send" + event + " to " + recipient, e);
1209 }
1210 }
1211
1212 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1213 try {
1214 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1215 } catch (IOException e) {
1216 log.error("Failed to send" + event + " to " + recipient, e);
1217 }
1218 }
1219
1220 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1221 try {
1222 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1223 } catch (IOException e) {
1224 log.error("Failed to send" + event + " to " + recipient, e);
1225 }
1226 }
1227
1228 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1229 try {
1230 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1231 } catch (IOException e) {
1232 log.error("Failed to send" + event + " to " + recipient, e);
1233 }
1234 }
1235
1236 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1237 final NodeId self = clusterService.getLocalNode().id();
1238
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001239 final int numDevices = deviceDescs.size();
1240 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1241 final int portsPerDevice = 8; // random factor to minimize reallocation
1242 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1243 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001244
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001245 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001246
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001247 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001248 synchronized (devDescs) {
1249
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001250 // send device offline timestamp
1251 Timestamp lOffline = this.offline.get(deviceId);
1252 if (lOffline != null) {
1253 adOffline.put(deviceId, lOffline);
1254 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001255
1256 for (Entry<ProviderId, DeviceDescriptions>
1257 prov : devDescs.entrySet()) {
1258
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001259 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001260 final ProviderId provId = prov.getKey();
1261 final DeviceDescriptions descs = prov.getValue();
1262
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001263 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001264 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001265
1266 for (Entry<PortNumber, Timestamped<PortDescription>>
1267 portDesc : descs.getPortDescs().entrySet()) {
1268
1269 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001270 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001271 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001272 }
1273 }
1274 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001275 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001276
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001277 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001278 }
1279
1280 /**
1281 * Responds to anti-entropy advertisement message.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001282 * <p/>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001283 * Notify sender about out-dated information using regular replication message.
1284 * Send back advertisement to sender if not in sync.
1285 *
1286 * @param advertisement to respond to
1287 */
1288 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1289
1290 final NodeId sender = advertisement.sender();
1291
1292 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1293 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1294 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1295
1296 // Fragments to request
1297 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1298 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1299
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001300 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001301 final DeviceId deviceId = de.getKey();
1302 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1303
1304 synchronized (lDevice) {
1305 // latestTimestamp across provider
1306 // Note: can be null initially
1307 Timestamp localLatest = offline.get(deviceId);
1308
1309 // handle device Ads
1310 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1311 final ProviderId provId = prov.getKey();
1312 final DeviceDescriptions lDeviceDescs = prov.getValue();
1313
1314 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1315
1316
1317 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1318 Timestamp advDevTimestamp = devAds.get(devFragId);
1319
Jonathan Hart403ea932015-02-20 16:23:00 -08001320 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1321 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001322 // remote does not have it or outdated, suggest
1323 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1324 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1325 // local is outdated, request
1326 reqDevices.add(devFragId);
1327 }
1328
1329 // handle port Ads
1330 for (Entry<PortNumber, Timestamped<PortDescription>>
1331 pe : lDeviceDescs.getPortDescs().entrySet()) {
1332
1333 final PortNumber num = pe.getKey();
1334 final Timestamped<PortDescription> lPort = pe.getValue();
1335
1336 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1337
1338 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001339 if (advPortTimestamp == null || lPort.isNewerThan(
1340 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001341 // remote does not have it or outdated, suggest
1342 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1343 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1344 // local is outdated, request
1345 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1346 reqPorts.add(portFragId);
1347 }
1348
1349 // remove port Ad already processed
1350 portAds.remove(portFragId);
1351 } // end local port loop
1352
1353 // remove device Ad already processed
1354 devAds.remove(devFragId);
1355
1356 // find latest and update
1357 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1358 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001359 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001360 localLatest = providerLatest;
1361 }
1362 } // end local provider loop
1363
1364 // checking if remote timestamp is more recent.
1365 Timestamp rOffline = offlineAds.get(deviceId);
1366 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001367 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001368 // remote offline timestamp suggests that the
1369 // device is off-line
1370 markOfflineInternal(deviceId, rOffline);
1371 }
1372
1373 Timestamp lOffline = offline.get(deviceId);
1374 if (lOffline != null && rOffline == null) {
1375 // locally offline, but remote is online, suggest offline
1376 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1377 }
1378
1379 // remove device offline Ad already processed
1380 offlineAds.remove(deviceId);
1381 } // end local device loop
1382 } // device lock
1383
1384 // If there is any Ads left, request them
1385 log.trace("Ads left {}, {}", devAds, portAds);
1386 reqDevices.addAll(devAds.keySet());
1387 reqPorts.addAll(portAds.keySet());
1388
1389 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1390 log.trace("Nothing to request to remote peer {}", sender);
1391 return;
1392 }
1393
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001394 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001395
1396 // 2-way Anti-Entropy for now
1397 try {
1398 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1399 } catch (IOException e) {
1400 log.error("Failed to send response advertisement to " + sender, e);
1401 }
1402
1403// Sketch of 3-way Anti-Entropy
1404// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1405// ClusterMessage message = new ClusterMessage(
1406// clusterService.getLocalNode().id(),
1407// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1408// SERIALIZER.encode(request));
1409//
1410// try {
1411// clusterCommunicator.unicast(message, advertisement.sender());
1412// } catch (IOException e) {
1413// log.error("Failed to send advertisement reply to "
1414// + advertisement.sender(), e);
1415// }
Madan Jampani47c93732014-10-06 20:46:08 -07001416 }
1417
Madan Jampani255a58b2014-10-09 12:08:20 -07001418 private void notifyDelegateIfNotNull(DeviceEvent event) {
1419 if (event != null) {
1420 notifyDelegate(event);
1421 }
1422 }
1423
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001424 private final class SendAdvertisementTask implements Runnable {
1425
1426 @Override
1427 public void run() {
1428 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001429 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001430 return;
1431 }
1432
1433 try {
1434 final NodeId self = clusterService.getLocalNode().id();
1435 Set<ControllerNode> nodes = clusterService.getNodes();
1436
1437 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1438 .transform(toNodeId())
1439 .toList();
1440
1441 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001442 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001443 return;
1444 }
1445
1446 NodeId peer;
1447 do {
1448 int idx = RandomUtils.nextInt(0, nodeIds.size());
1449 peer = nodeIds.get(idx);
1450 } while (peer.equals(self));
1451
1452 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1453
1454 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001455 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001456 return;
1457 }
1458
1459 try {
1460 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1461 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001462 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001463 return;
1464 }
1465 } catch (Exception e) {
1466 // catch all Exception to avoid Scheduled task being suppressed.
1467 log.error("Exception thrown while sending advertisement", e);
1468 }
1469 }
1470 }
1471
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001472 private final class InternalDeviceEventListener
1473 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001474 @Override
1475 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001476 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001477 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001478
Madan Jampani47c93732014-10-06 20:46:08 -07001479 ProviderId providerId = event.providerId();
1480 DeviceId deviceId = event.deviceId();
1481 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001482
Madan Jampani2af244a2015-02-22 13:12:01 -08001483 try {
1484 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1485 } catch (Exception e) {
1486 log.warn("Exception thrown handling device update", e);
1487 }
Madan Jampani47c93732014-10-06 20:46:08 -07001488 }
1489 }
1490
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001491 private final class InternalDeviceOfflineEventListener
1492 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001493 @Override
1494 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001495 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001496 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001497
1498 DeviceId deviceId = event.deviceId();
1499 Timestamp timestamp = event.timestamp();
1500
Madan Jampani2af244a2015-02-22 13:12:01 -08001501 try {
1502 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1503 } catch (Exception e) {
1504 log.warn("Exception thrown handling device offline", e);
1505 }
Madan Jampani25322532014-10-08 11:20:38 -07001506 }
1507 }
1508
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001509 private final class InternalRemoveRequestListener
1510 implements ClusterMessageHandler {
1511 @Override
1512 public void handle(ClusterMessage message) {
1513 log.debug("Received device remove request from peer: {}", message.sender());
1514 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001515
Madan Jampani2af244a2015-02-22 13:12:01 -08001516 try {
1517 removeDevice(did);
1518 } catch (Exception e) {
1519 log.warn("Exception thrown handling device remove", e);
1520 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001521 }
1522 }
1523
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001524 private final class InternalDeviceRemovedEventListener
1525 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001526 @Override
1527 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001528 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001529 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001530
1531 DeviceId deviceId = event.deviceId();
1532 Timestamp timestamp = event.timestamp();
1533
Madan Jampani2af244a2015-02-22 13:12:01 -08001534 try {
1535 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1536 } catch (Exception e) {
1537 log.warn("Exception thrown handling device removed", e);
1538 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001539 }
1540 }
1541
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001542 private final class InternalPortEventListener
1543 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001544 @Override
1545 public void handle(ClusterMessage message) {
1546
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001547 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001548 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001549
1550 ProviderId providerId = event.providerId();
1551 DeviceId deviceId = event.deviceId();
1552 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1553
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001554 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001555 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001556 // Note: dropped information will be recovered by anti-entropy
1557 return;
1558 }
1559
Madan Jampani2af244a2015-02-22 13:12:01 -08001560 try {
1561 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1562 } catch (Exception e) {
1563 log.warn("Exception thrown handling port update", e);
1564 }
Madan Jampani47c93732014-10-06 20:46:08 -07001565 }
1566 }
1567
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001568 private final class InternalPortStatusEventListener
1569 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001570 @Override
1571 public void handle(ClusterMessage message) {
1572
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001573 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001574 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001575
1576 ProviderId providerId = event.providerId();
1577 DeviceId deviceId = event.deviceId();
1578 Timestamped<PortDescription> portDescription = event.portDescription();
1579
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001580 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001581 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001582 // Note: dropped information will be recovered by anti-entropy
1583 return;
1584 }
1585
Madan Jampani2af244a2015-02-22 13:12:01 -08001586 try {
1587 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1588 } catch (Exception e) {
1589 log.warn("Exception thrown handling port update", e);
1590 }
Madan Jampani47c93732014-10-06 20:46:08 -07001591 }
1592 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001593
1594 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001595 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001596 @Override
1597 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001598 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001599 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001600 try {
1601 handleAdvertisement(advertisement);
1602 } catch (Exception e) {
1603 log.warn("Exception thrown handling Device advertisements.", e);
1604 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001605 }
1606 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001607
1608 private final class DeviceInjectedEventListener
1609 implements ClusterMessageHandler {
1610 @Override
1611 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001612 log.debug("Received injected device event from peer: {}", message.sender());
1613 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1614
1615 ProviderId providerId = event.providerId();
1616 DeviceId deviceId = event.deviceId();
1617 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001618 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1619 // workaround for ONOS-1208
1620 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1621 return;
1622 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001623
Madan Jampani2af244a2015-02-22 13:12:01 -08001624 try {
1625 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1626 } catch (Exception e) {
1627 log.warn("Exception thrown handling device injected event.", e);
1628 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001629 }
1630 }
1631
1632 private final class PortInjectedEventListener
1633 implements ClusterMessageHandler {
1634 @Override
1635 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001636 log.debug("Received injected port event from peer: {}", message.sender());
1637 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1638
1639 ProviderId providerId = event.providerId();
1640 DeviceId deviceId = event.deviceId();
1641 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001642 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1643 // workaround for ONOS-1208
1644 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1645 return;
1646 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001647
Madan Jampani2af244a2015-02-22 13:12:01 -08001648 try {
1649 updatePorts(providerId, deviceId, portDescriptions);
1650 } catch (Exception e) {
1651 log.warn("Exception thrown handling port injected event.", e);
1652 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001653 }
1654 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001655
1656 private class InternalPortStatsListener
1657 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1658 @Override
1659 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1660 if (event.type() == PUT) {
1661 Device device = devices.get(event.key());
1662 if (device != null) {
1663 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1664 }
1665 }
1666 }
1667 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001668}