blob: 0b4e215136b0b525c5d5cefcf87dd27c54083916 [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
Yuta HIGUCHI47c40882014-10-10 18:44:37 -070018import com.google.common.base.Function;
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -080019import com.google.common.base.Predicate;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070020import com.google.common.collect.FluentIterable;
21import com.google.common.collect.ImmutableList;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -070022import com.google.common.collect.Maps;
23import com.google.common.collect.Sets;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070024import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070025import org.apache.felix.scr.annotations.Activate;
26import org.apache.felix.scr.annotations.Component;
27import org.apache.felix.scr.annotations.Deactivate;
28import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
30import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080031import org.onlab.packet.ChassisId;
32import org.onlab.util.KryoNamespace;
33import org.onlab.util.NewConcurrentHashMap;
Brian O'Connorabafb502014-12-02 22:26:20 -080034import org.onosproject.cluster.ClusterService;
35import org.onosproject.cluster.ControllerNode;
36import org.onosproject.cluster.NodeId;
37import org.onosproject.mastership.MastershipService;
38import org.onosproject.mastership.MastershipTerm;
39import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070040import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080041import org.onosproject.net.AnnotationsUtil;
42import org.onosproject.net.DefaultAnnotations;
43import org.onosproject.net.DefaultDevice;
44import org.onosproject.net.DefaultPort;
45import org.onosproject.net.Device;
46import org.onosproject.net.Device.Type;
47import org.onosproject.net.DeviceId;
48import org.onosproject.net.MastershipRole;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070049import org.onosproject.net.OchPort;
50import org.onosproject.net.OduCltPort;
51import org.onosproject.net.OmsPort;
Brian O'Connorabafb502014-12-02 22:26:20 -080052import org.onosproject.net.Port;
53import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070054import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.net.device.DeviceClockService;
56import org.onosproject.net.device.DeviceDescription;
57import org.onosproject.net.device.DeviceEvent;
58import org.onosproject.net.device.DeviceStore;
59import org.onosproject.net.device.DeviceStoreDelegate;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070060import org.onosproject.net.device.OchPortDescription;
61import org.onosproject.net.device.OduCltPortDescription;
62import org.onosproject.net.device.OmsPortDescription;
Brian O'Connorabafb502014-12-02 22:26:20 -080063import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070064import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080065import org.onosproject.net.provider.ProviderId;
66import org.onosproject.store.AbstractStore;
67import org.onosproject.store.Timestamp;
68import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
69import org.onosproject.store.cluster.messaging.ClusterMessage;
70import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
71import org.onosproject.store.cluster.messaging.MessageSubject;
72import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070073import org.onosproject.store.serializers.KryoNamespaces;
Brian O'Connorabafb502014-12-02 22:26:20 -080074import org.onosproject.store.serializers.KryoSerializer;
Brian O'Connor6de2e202015-05-21 14:30:41 -070075import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070076import org.onosproject.store.service.EventuallyConsistentMap;
77import org.onosproject.store.service.EventuallyConsistentMapEvent;
78import org.onosproject.store.service.EventuallyConsistentMapListener;
79import org.onosproject.store.service.MultiValuedTimestamp;
80import org.onosproject.store.service.StorageService;
81import org.onosproject.store.service.WallClockTimestamp;
82import org.onosproject.store.service.WallclockClockManager;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070083import org.slf4j.Logger;
84
Madan Jampani47c93732014-10-06 20:46:08 -070085import java.io.IOException;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070086import java.util.ArrayList;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070087import java.util.Collection;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070088import java.util.Collections;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070089import java.util.HashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070090import java.util.HashSet;
91import java.util.Iterator;
92import java.util.List;
93import java.util.Map;
94import java.util.Map.Entry;
95import java.util.Objects;
96import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070097import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080098import java.util.concurrent.ExecutorService;
99import java.util.concurrent.Executors;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700100import java.util.concurrent.ScheduledExecutorService;
101import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700102
103import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700104import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700105import static com.google.common.base.Verify.verify;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800106import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
107import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800108import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800109import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800110import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
111import static org.onosproject.net.DefaultAnnotations.merge;
112import static org.onosproject.net.device.DeviceEvent.Type.*;
113import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
114import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700115import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800116import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700117
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700118/**
119 * Manages inventory of infrastructure devices using gossip protocol to distribute
120 * information.
121 */
122@Component(immediate = true)
123@Service
124public class GossipDeviceStore
125 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
126 implements DeviceStore {
127
128 private final Logger log = getLogger(getClass());
129
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700130 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800131 // Timeout in milliseconds to process device or ports on remote master node
132 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700133
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700134 // innerMap is used to lock a Device, thus instance should never be replaced.
135 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700136 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700137 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700138
139 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700140 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
141 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700142
143 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
144 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
145 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700146
147 // to be updated under Device lock
148 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
149 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700150
151 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700152 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700153
154 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700155 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700156
Madan Jampani47c93732014-10-06 20:46:08 -0700157 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700158 protected StorageService storageService;
159
160 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700161 protected ClusterCommunicationService clusterCommunicator;
162
Madan Jampani53e44e62014-10-07 12:39:51 -0700163 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
164 protected ClusterService clusterService;
165
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700166 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
167 protected MastershipService mastershipService;
168
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800169 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
170 protected MastershipTermService termService;
171
172
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700173 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700174 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700175 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700176 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800177 .register(DistributedStoreSerializers.STORE_COMMON)
178 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
179 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
180 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700181 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800182 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
183 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700184 .register(DeviceAntiEntropyAdvertisement.class)
185 .register(DeviceFragmentId.class)
186 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800187 .register(DeviceInjectedEvent.class)
188 .register(PortInjectedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800189 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700190 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700191 };
192
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800193 private ExecutorService executor;
194
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800195 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700196
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800197 // TODO make these anti-entropy parameters configurable
198 private long initialDelaySec = 5;
199 private long periodSec = 5;
200
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700201 @Activate
202 public void activate() {
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800203 executor = Executors.newCachedThreadPool(groupedThreads("onos/device", "fg-%d"));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800204
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800205 backgroundExecutor =
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800206 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700207
Madan Jampani2af244a2015-02-22 13:12:01 -0800208 clusterCommunicator.addSubscriber(
209 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
210 clusterCommunicator.addSubscriber(
211 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
212 new InternalDeviceOfflineEventListener(),
213 executor);
214 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700215 new InternalRemoveRequestListener(),
216 executor);
Madan Jampani2af244a2015-02-22 13:12:01 -0800217 clusterCommunicator.addSubscriber(
218 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
219 clusterCommunicator.addSubscriber(
220 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
221 clusterCommunicator.addSubscriber(
222 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
223 clusterCommunicator.addSubscriber(
224 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
225 new InternalDeviceAdvertisementListener(),
226 backgroundExecutor);
227 clusterCommunicator.addSubscriber(
228 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
229 clusterCommunicator.addSubscriber(
230 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
231
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700232 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800233 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700234 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700235
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700236 // Create a distributed map for port stats.
237 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
238 .register(KryoNamespaces.API)
239 .register(DefaultPortStatistics.class)
240 .register(DeviceId.class)
241 .register(MultiValuedTimestamp.class)
242 .register(WallClockTimestamp.class);
243
244 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
245 .withName("port-stats")
246 .withSerializer(deviceDataSerializer)
247 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
248 .withClockService(new WallclockClockManager<>())
249 .withTombstonesDisabled()
250 .build();
251 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700252 log.info("Started");
253 }
254
255 @Deactivate
256 public void deactivate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700257
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800258 executor.shutdownNow();
259
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800260 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700261 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800262 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700263 log.error("Timeout during executor shutdown");
264 }
265 } catch (InterruptedException e) {
266 log.error("Error during executor shutdown", e);
267 }
268
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700269 deviceDescs.clear();
270 devices.clear();
271 devicePorts.clear();
272 availableDevices.clear();
273 log.info("Stopped");
274 }
275
276 @Override
277 public int getDeviceCount() {
278 return devices.size();
279 }
280
281 @Override
282 public Iterable<Device> getDevices() {
283 return Collections.unmodifiableCollection(devices.values());
284 }
285
286 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800287 public Iterable<Device> getAvailableDevices() {
288 return FluentIterable.from(getDevices())
289 .filter(new Predicate<Device>() {
290
291 @Override
292 public boolean apply(Device input) {
293 return isAvailable(input.id());
294 }
295 });
296 }
297
298 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700299 public Device getDevice(DeviceId deviceId) {
300 return devices.get(deviceId);
301 }
302
303 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700304 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700305 DeviceId deviceId,
306 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800307 NodeId localNode = clusterService.getLocalNode().id();
308 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
309
310 // Process device update only if we're the master,
311 // otherwise signal the actual master.
312 DeviceEvent deviceEvent = null;
313 if (localNode.equals(deviceNode)) {
314
315 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
316 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
317 final Timestamped<DeviceDescription> mergedDesc;
318 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
319
320 synchronized (device) {
321 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
322 mergedDesc = device.get(providerId).getDeviceDesc();
323 }
324
325 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700326 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700327 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800328 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
329 }
330
331 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800332 // FIXME Temporary hack for NPE (ONOS-1171).
333 // Proper fix is to implement forwarding to master on ConfigProvider
334 // redo ONOS-490
335 if (deviceNode == null) {
336 // silently ignore
337 return null;
338 }
339
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800340
341 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
342 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800343
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800344 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700345 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800346 /* error log:
347 log.warn("Failed to process injected device id: {} desc: {} " +
348 "(cluster messaging failed: {})",
349 deviceId, deviceDescription, e);
350 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700351 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800352
353 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700354 }
355
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700356 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700357 DeviceId deviceId,
358 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700359
360 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800361 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700362 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700363
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800364 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700365 // locking per device
366
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700367 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
368 log.debug("Ignoring outdated event: {}", deltaDesc);
369 return null;
370 }
371
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800372 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700373
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700374 final Device oldDevice = devices.get(deviceId);
375 final Device newDevice;
376
377 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700378 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700379 // on new device or valid update
380 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800381 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700382 } else {
383 // outdated event, ignored.
384 return null;
385 }
386 if (oldDevice == null) {
387 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700388 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700389 } else {
390 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700391 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700392 }
393 }
394 }
395
396 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700397 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700398 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700399 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700400
401 // update composed device cache
402 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
403 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700404 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
405 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700406
407 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700408 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700409 }
410
411 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
412 }
413
414 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700415 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700416 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700417 Device oldDevice,
418 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700419 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700420 boolean propertiesChanged =
421 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700422 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
423 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700424 boolean annotationsChanged =
425 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700426
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700427 // Primary providers can respond to all changes, but ancillary ones
428 // should respond only to annotation changes.
429 if ((providerId.isAncillary() && annotationsChanged) ||
430 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700431 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
432 if (!replaced) {
433 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700434 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
435 providerId, oldDevice, devices.get(newDevice.id())
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700436 , newDevice);
437 }
438 if (!providerId.isAncillary()) {
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700439 boolean wasOnline = availableDevices.contains(newDevice.id());
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700440 markOnline(newDevice.id(), newTimestamp);
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700441 if (!wasOnline) {
442 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
443 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700444 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700445
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700446 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700447 }
448 return null;
449 }
450
451 @Override
452 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700453 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700454 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700455 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700456 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700457 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800458 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700459 }
460 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700461 }
462
463 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
464
465 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700466 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700467
468 // locking device
469 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700470
471 // accept off-line if given timestamp is newer than
472 // the latest Timestamp from Primary provider
473 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
474 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
475 if (timestamp.compareTo(lastTimestamp) <= 0) {
476 // outdated event ignore
477 return null;
478 }
479
480 offline.put(deviceId, timestamp);
481
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700482 Device device = devices.get(deviceId);
483 if (device == null) {
484 return null;
485 }
486 boolean removed = availableDevices.remove(deviceId);
487 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700488 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700489 }
490 return null;
491 }
492 }
493
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700494 /**
495 * Marks the device as available if the given timestamp is not outdated,
496 * compared to the time the device has been marked offline.
497 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700498 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700499 * @param timestamp of the event triggering this change.
500 * @return true if availability change request was accepted and changed the state
501 */
502 // Guarded by deviceDescs value (=Device lock)
503 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
504 // accept on-line if given timestamp is newer than
505 // the latest offline request Timestamp
506 Timestamp offlineTimestamp = offline.get(deviceId);
507 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700508 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700509
510 offline.remove(deviceId);
511 return availableDevices.add(deviceId);
512 }
513 return false;
514 }
515
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700516 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700517 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700518 DeviceId deviceId,
519 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700520
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800521 NodeId localNode = clusterService.getLocalNode().id();
522 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
523 // since it will trigger distributed store read.
524 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
525 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
526 // If we don't care much about topology performance, then it might be OK.
527 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700528
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800529 // Process port update only if we're the master of the device,
530 // otherwise signal the actual master.
531 List<DeviceEvent> deviceEvents = null;
532 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700533
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800534 final Timestamp newTimestamp;
535 try {
536 newTimestamp = deviceClockService.getTimestamp(deviceId);
537 } catch (IllegalStateException e) {
538 log.info("Timestamp was not available for device {}", deviceId);
539 log.debug(" discarding {}", portDescriptions);
540 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700541
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800542 // Possible situation:
543 // Device connected and became master for short period of time,
544 // but lost mastership before this instance had the chance to
545 // retrieve term information.
546
547 // Information dropped here is expected to be recoverable by
548 // device probing after mastership change
549
550 return Collections.emptyList();
551 }
552 log.debug("timestamp for {} {}", deviceId, newTimestamp);
553
554 final Timestamped<List<PortDescription>> timestampedInput
555 = new Timestamped<>(portDescriptions, newTimestamp);
556 final Timestamped<List<PortDescription>> merged;
557
558 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
559
560 synchronized (device) {
561 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
562 final DeviceDescriptions descs = device.get(providerId);
563 List<PortDescription> mergedList =
564 FluentIterable.from(portDescriptions)
565 .transform(new Function<PortDescription, PortDescription>() {
566 @Override
567 public PortDescription apply(PortDescription input) {
568 // lookup merged port description
569 return descs.getPortDesc(input.portNumber()).value();
570 }
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);
619 return null;
620 }
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,
835 Collection<PortStatistics> portStats) {
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700836 Map<PortNumber, PortStatistics> statsMap = devicePortStats.get(deviceId);
sangho538108b2015-04-08 14:29:20 -0700837 if (statsMap == null) {
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700838 statsMap = Maps.newHashMap();
sangho538108b2015-04-08 14:29:20 -0700839 }
840
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700841 for (PortStatistics stat : portStats) {
sangho538108b2015-04-08 14:29:20 -0700842 PortNumber portNumber = PortNumber.portNumber(stat.port());
843 statsMap.put(portNumber, stat);
844 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700845 devicePortStats.put(deviceId, statsMap);
846 return null; // new DeviceEvent(PORT_STATS_UPDATED, devices.get(deviceId), null);
sangho538108b2015-04-08 14:29:20 -0700847 }
848
849 @Override
850 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700851 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
852 if (portStats == null) {
853 return Collections.emptyList();
854 }
855 return ImmutableList.copyOf(portStats.values());
856 }
857
858 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700859 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
860 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
861 return ports == null ? null : ports.get(portNumber);
862 }
863
864 @Override
865 public boolean isAvailable(DeviceId deviceId) {
866 return availableDevices.contains(deviceId);
867 }
868
869 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700870 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800871 final NodeId myId = clusterService.getLocalNode().id();
872 NodeId master = mastershipService.getMasterFor(deviceId);
873
874 // if there exist a master, forward
875 // if there is no master, try to become one and process
876
877 boolean relinquishAtEnd = false;
878 if (master == null) {
879 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
880 if (myRole != MastershipRole.NONE) {
881 relinquishAtEnd = true;
882 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800883 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800884 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800885 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700886 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800887 master = myId;
888 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700889 }
890
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800891 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800892 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700893 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800894
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800895 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700896 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800897 /* error log:
898 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
899 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800900
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800901 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700902 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800903 }
904
905 // I have control..
906
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700907 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700908 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700909 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800910 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700911 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800912 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700913 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800914 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800915 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800916 mastershipService.relinquishMastership(deviceId);
917 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700918 return event;
919 }
920
921 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
922 Timestamp timestamp) {
923
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700924 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700925 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700926 // accept removal request if given timestamp is newer than
927 // the latest Timestamp from Primary provider
928 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
929 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
930 if (timestamp.compareTo(lastTimestamp) <= 0) {
931 // outdated event ignore
932 return null;
933 }
934 removalRequest.put(deviceId, timestamp);
935
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700936 Device device = devices.remove(deviceId);
937 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700938 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
939 if (ports != null) {
940 ports.clear();
941 }
942 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700943 descs.clear();
944 return device == null ? null :
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700945 new DeviceEvent(DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700946 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700947 }
948
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700949 /**
950 * Checks if given timestamp is superseded by removal request
951 * with more recent timestamp.
952 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700953 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700954 * @param timestampToCheck timestamp of an event to check
955 * @return true if device is already removed
956 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700957 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
958 Timestamp removalTimestamp = removalRequest.get(deviceId);
959 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700960 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700961 // removalRequest is more recent
962 return true;
963 }
964 return false;
965 }
966
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700967 /**
968 * Returns a Device, merging description given from multiple Providers.
969 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700970 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700971 * @param providerDescs Collection of Descriptions from multiple providers
972 * @return Device instance
973 */
974 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700975 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700976
Thomas Vachuska444eda62014-10-28 13:09:42 -0700977 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700978
979 ProviderId primary = pickPrimaryPID(providerDescs);
980
981 DeviceDescriptions desc = providerDescs.get(primary);
982
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700983 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700984 Type type = base.type();
985 String manufacturer = base.manufacturer();
986 String hwVersion = base.hwVersion();
987 String swVersion = base.swVersion();
988 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700989 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700990 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
991 annotations = merge(annotations, base.annotations());
992
993 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
994 if (e.getKey().equals(primary)) {
995 continue;
996 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800997 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700998 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700999 // Currently assuming there will never be a key conflict between
1000 // providers
1001
1002 // annotation merging. not so efficient, should revisit later
1003 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1004 }
1005
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001006 return new DefaultDevice(primary, deviceId, type, manufacturer,
1007 hwVersion, swVersion, serialNumber,
1008 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001009 }
1010
Marc De Leenheer88194c32015-05-29 22:10:59 -07001011 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1012 PortDescription description, Annotations annotations) {
1013 switch (description.type()) {
1014 case OMS:
1015 OmsPortDescription omsDesc = (OmsPortDescription) description;
1016 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1017 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1018 case OCH:
1019 OchPortDescription ochDesc = (OchPortDescription) description;
1020 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1021 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1022 case ODUCLT:
1023 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1024 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1025 default:
1026 return new DefaultPort(device, number, isEnabled, description.type(),
1027 description.portSpeed(), annotations);
1028 }
1029 }
1030
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001031 /**
1032 * Returns a Port, merging description given from multiple Providers.
1033 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001034 * @param device device the port is on
1035 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001036 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001037 * @return Port instance
1038 */
1039 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001040 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001041
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001042 ProviderId primary = pickPrimaryPID(descsMap);
1043 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001044 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001045 boolean isEnabled = false;
1046 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001047 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001048 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1049 if (portDesc != null) {
1050 isEnabled = portDesc.value().isEnabled();
1051 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001052 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001053 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001054 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001055 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001056 if (e.getKey().equals(primary)) {
1057 continue;
1058 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001059 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001060 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001061 // Currently assuming there will never be a key conflict between
1062 // providers
1063
1064 // annotation merging. not so efficient, should revisit later
1065 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1066 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001067 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1068 continue;
1069 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001070 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001071 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001072 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001073 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001074 }
1075 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001076 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001077 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001078 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001079 PortDescription current = portDesc.value();
1080 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001081 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001082 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001083 }
1084
1085 /**
1086 * @return primary ProviderID, or randomly chosen one if none exists
1087 */
1088 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001089 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001090 ProviderId fallBackPrimary = null;
1091 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1092 if (!e.getKey().isAncillary()) {
1093 return e.getKey();
1094 } else if (fallBackPrimary == null) {
1095 // pick randomly as a fallback in case there is no primary
1096 fallBackPrimary = e.getKey();
1097 }
1098 }
1099 return fallBackPrimary;
1100 }
1101
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001102 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001103 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001104 ProviderId pid = pickPrimaryPID(providerDescs);
1105 return providerDescs.get(pid);
1106 }
1107
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001108 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001109 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001110 }
1111
Jonathan Hart7d656f42015-01-27 14:07:23 -08001112 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001113 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001114 }
Madan Jampani47c93732014-10-06 20:46:08 -07001115
Jonathan Hart7d656f42015-01-27 14:07:23 -08001116 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001117 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001118 }
1119
Jonathan Hart7d656f42015-01-27 14:07:23 -08001120 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001121 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001122 }
1123
Jonathan Hart7d656f42015-01-27 14:07:23 -08001124 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001125 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001126 }
1127
Jonathan Hart7d656f42015-01-27 14:07:23 -08001128 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001129 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001130 }
1131
Jonathan Hart7d656f42015-01-27 14:07:23 -08001132 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001133 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1134 }
1135
1136 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1137 try {
1138 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1139 } catch (IOException e) {
1140 log.error("Failed to send" + event + " to " + recipient, e);
1141 }
1142 }
1143
1144 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1145 try {
1146 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1147 } catch (IOException e) {
1148 log.error("Failed to send" + event + " to " + recipient, e);
1149 }
1150 }
1151
1152 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1153 try {
1154 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1155 } catch (IOException e) {
1156 log.error("Failed to send" + event + " to " + recipient, e);
1157 }
1158 }
1159
1160 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1161 try {
1162 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1163 } catch (IOException e) {
1164 log.error("Failed to send" + event + " to " + recipient, e);
1165 }
1166 }
1167
1168 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1169 try {
1170 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1171 } catch (IOException e) {
1172 log.error("Failed to send" + event + " to " + recipient, e);
1173 }
1174 }
1175
1176 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1177 final NodeId self = clusterService.getLocalNode().id();
1178
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001179 final int numDevices = deviceDescs.size();
1180 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1181 final int portsPerDevice = 8; // random factor to minimize reallocation
1182 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1183 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001184
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001185 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001186
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001187 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001188 synchronized (devDescs) {
1189
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001190 // send device offline timestamp
1191 Timestamp lOffline = this.offline.get(deviceId);
1192 if (lOffline != null) {
1193 adOffline.put(deviceId, lOffline);
1194 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001195
1196 for (Entry<ProviderId, DeviceDescriptions>
1197 prov : devDescs.entrySet()) {
1198
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001199 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001200 final ProviderId provId = prov.getKey();
1201 final DeviceDescriptions descs = prov.getValue();
1202
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001203 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001204 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001205
1206 for (Entry<PortNumber, Timestamped<PortDescription>>
1207 portDesc : descs.getPortDescs().entrySet()) {
1208
1209 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001210 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001211 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001212 }
1213 }
1214 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001215 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001216
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001217 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001218 }
1219
1220 /**
1221 * Responds to anti-entropy advertisement message.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001222 * <p/>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001223 * Notify sender about out-dated information using regular replication message.
1224 * Send back advertisement to sender if not in sync.
1225 *
1226 * @param advertisement to respond to
1227 */
1228 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1229
1230 final NodeId sender = advertisement.sender();
1231
1232 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1233 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1234 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1235
1236 // Fragments to request
1237 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1238 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1239
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001240 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001241 final DeviceId deviceId = de.getKey();
1242 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1243
1244 synchronized (lDevice) {
1245 // latestTimestamp across provider
1246 // Note: can be null initially
1247 Timestamp localLatest = offline.get(deviceId);
1248
1249 // handle device Ads
1250 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1251 final ProviderId provId = prov.getKey();
1252 final DeviceDescriptions lDeviceDescs = prov.getValue();
1253
1254 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1255
1256
1257 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1258 Timestamp advDevTimestamp = devAds.get(devFragId);
1259
Jonathan Hart403ea932015-02-20 16:23:00 -08001260 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1261 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001262 // remote does not have it or outdated, suggest
1263 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1264 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1265 // local is outdated, request
1266 reqDevices.add(devFragId);
1267 }
1268
1269 // handle port Ads
1270 for (Entry<PortNumber, Timestamped<PortDescription>>
1271 pe : lDeviceDescs.getPortDescs().entrySet()) {
1272
1273 final PortNumber num = pe.getKey();
1274 final Timestamped<PortDescription> lPort = pe.getValue();
1275
1276 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1277
1278 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001279 if (advPortTimestamp == null || lPort.isNewerThan(
1280 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001281 // remote does not have it or outdated, suggest
1282 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1283 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1284 // local is outdated, request
1285 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1286 reqPorts.add(portFragId);
1287 }
1288
1289 // remove port Ad already processed
1290 portAds.remove(portFragId);
1291 } // end local port loop
1292
1293 // remove device Ad already processed
1294 devAds.remove(devFragId);
1295
1296 // find latest and update
1297 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1298 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001299 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001300 localLatest = providerLatest;
1301 }
1302 } // end local provider loop
1303
1304 // checking if remote timestamp is more recent.
1305 Timestamp rOffline = offlineAds.get(deviceId);
1306 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001307 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001308 // remote offline timestamp suggests that the
1309 // device is off-line
1310 markOfflineInternal(deviceId, rOffline);
1311 }
1312
1313 Timestamp lOffline = offline.get(deviceId);
1314 if (lOffline != null && rOffline == null) {
1315 // locally offline, but remote is online, suggest offline
1316 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1317 }
1318
1319 // remove device offline Ad already processed
1320 offlineAds.remove(deviceId);
1321 } // end local device loop
1322 } // device lock
1323
1324 // If there is any Ads left, request them
1325 log.trace("Ads left {}, {}", devAds, portAds);
1326 reqDevices.addAll(devAds.keySet());
1327 reqPorts.addAll(portAds.keySet());
1328
1329 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1330 log.trace("Nothing to request to remote peer {}", sender);
1331 return;
1332 }
1333
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001334 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001335
1336 // 2-way Anti-Entropy for now
1337 try {
1338 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1339 } catch (IOException e) {
1340 log.error("Failed to send response advertisement to " + sender, e);
1341 }
1342
1343// Sketch of 3-way Anti-Entropy
1344// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1345// ClusterMessage message = new ClusterMessage(
1346// clusterService.getLocalNode().id(),
1347// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1348// SERIALIZER.encode(request));
1349//
1350// try {
1351// clusterCommunicator.unicast(message, advertisement.sender());
1352// } catch (IOException e) {
1353// log.error("Failed to send advertisement reply to "
1354// + advertisement.sender(), e);
1355// }
Madan Jampani47c93732014-10-06 20:46:08 -07001356 }
1357
Madan Jampani255a58b2014-10-09 12:08:20 -07001358 private void notifyDelegateIfNotNull(DeviceEvent event) {
1359 if (event != null) {
1360 notifyDelegate(event);
1361 }
1362 }
1363
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001364 private final class SendAdvertisementTask implements Runnable {
1365
1366 @Override
1367 public void run() {
1368 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001369 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001370 return;
1371 }
1372
1373 try {
1374 final NodeId self = clusterService.getLocalNode().id();
1375 Set<ControllerNode> nodes = clusterService.getNodes();
1376
1377 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1378 .transform(toNodeId())
1379 .toList();
1380
1381 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001382 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001383 return;
1384 }
1385
1386 NodeId peer;
1387 do {
1388 int idx = RandomUtils.nextInt(0, nodeIds.size());
1389 peer = nodeIds.get(idx);
1390 } while (peer.equals(self));
1391
1392 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1393
1394 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001395 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001396 return;
1397 }
1398
1399 try {
1400 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1401 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001402 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001403 return;
1404 }
1405 } catch (Exception e) {
1406 // catch all Exception to avoid Scheduled task being suppressed.
1407 log.error("Exception thrown while sending advertisement", e);
1408 }
1409 }
1410 }
1411
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001412 private final class InternalDeviceEventListener
1413 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001414 @Override
1415 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001416 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001417 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001418
Madan Jampani47c93732014-10-06 20:46:08 -07001419 ProviderId providerId = event.providerId();
1420 DeviceId deviceId = event.deviceId();
1421 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001422
Madan Jampani2af244a2015-02-22 13:12:01 -08001423 try {
1424 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1425 } catch (Exception e) {
1426 log.warn("Exception thrown handling device update", e);
1427 }
Madan Jampani47c93732014-10-06 20:46:08 -07001428 }
1429 }
1430
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001431 private final class InternalDeviceOfflineEventListener
1432 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001433 @Override
1434 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001435 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001436 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001437
1438 DeviceId deviceId = event.deviceId();
1439 Timestamp timestamp = event.timestamp();
1440
Madan Jampani2af244a2015-02-22 13:12:01 -08001441 try {
1442 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1443 } catch (Exception e) {
1444 log.warn("Exception thrown handling device offline", e);
1445 }
Madan Jampani25322532014-10-08 11:20:38 -07001446 }
1447 }
1448
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001449 private final class InternalRemoveRequestListener
1450 implements ClusterMessageHandler {
1451 @Override
1452 public void handle(ClusterMessage message) {
1453 log.debug("Received device remove request from peer: {}", message.sender());
1454 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001455
Madan Jampani2af244a2015-02-22 13:12:01 -08001456 try {
1457 removeDevice(did);
1458 } catch (Exception e) {
1459 log.warn("Exception thrown handling device remove", e);
1460 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001461 }
1462 }
1463
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001464 private final class InternalDeviceRemovedEventListener
1465 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001466 @Override
1467 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001468 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001469 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001470
1471 DeviceId deviceId = event.deviceId();
1472 Timestamp timestamp = event.timestamp();
1473
Madan Jampani2af244a2015-02-22 13:12:01 -08001474 try {
1475 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1476 } catch (Exception e) {
1477 log.warn("Exception thrown handling device removed", e);
1478 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001479 }
1480 }
1481
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001482 private final class InternalPortEventListener
1483 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001484 @Override
1485 public void handle(ClusterMessage message) {
1486
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001487 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001488 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001489
1490 ProviderId providerId = event.providerId();
1491 DeviceId deviceId = event.deviceId();
1492 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1493
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001494 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001495 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001496 // Note: dropped information will be recovered by anti-entropy
1497 return;
1498 }
1499
Madan Jampani2af244a2015-02-22 13:12:01 -08001500 try {
1501 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1502 } catch (Exception e) {
1503 log.warn("Exception thrown handling port update", e);
1504 }
Madan Jampani47c93732014-10-06 20:46:08 -07001505 }
1506 }
1507
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001508 private final class InternalPortStatusEventListener
1509 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001510 @Override
1511 public void handle(ClusterMessage message) {
1512
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001513 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001514 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001515
1516 ProviderId providerId = event.providerId();
1517 DeviceId deviceId = event.deviceId();
1518 Timestamped<PortDescription> portDescription = event.portDescription();
1519
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001520 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001521 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001522 // Note: dropped information will be recovered by anti-entropy
1523 return;
1524 }
1525
Madan Jampani2af244a2015-02-22 13:12:01 -08001526 try {
1527 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1528 } catch (Exception e) {
1529 log.warn("Exception thrown handling port update", e);
1530 }
Madan Jampani47c93732014-10-06 20:46:08 -07001531 }
1532 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001533
1534 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001535 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001536 @Override
1537 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001538 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001539 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001540 try {
1541 handleAdvertisement(advertisement);
1542 } catch (Exception e) {
1543 log.warn("Exception thrown handling Device advertisements.", e);
1544 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001545 }
1546 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001547
1548 private final class DeviceInjectedEventListener
1549 implements ClusterMessageHandler {
1550 @Override
1551 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001552 log.debug("Received injected device event from peer: {}", message.sender());
1553 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1554
1555 ProviderId providerId = event.providerId();
1556 DeviceId deviceId = event.deviceId();
1557 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001558 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1559 // workaround for ONOS-1208
1560 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1561 return;
1562 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001563
Madan Jampani2af244a2015-02-22 13:12:01 -08001564 try {
1565 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1566 } catch (Exception e) {
1567 log.warn("Exception thrown handling device injected event.", e);
1568 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001569 }
1570 }
1571
1572 private final class PortInjectedEventListener
1573 implements ClusterMessageHandler {
1574 @Override
1575 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001576 log.debug("Received injected port event from peer: {}", message.sender());
1577 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1578
1579 ProviderId providerId = event.providerId();
1580 DeviceId deviceId = event.deviceId();
1581 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001582 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1583 // workaround for ONOS-1208
1584 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1585 return;
1586 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001587
Madan Jampani2af244a2015-02-22 13:12:01 -08001588 try {
1589 updatePorts(providerId, deviceId, portDescriptions);
1590 } catch (Exception e) {
1591 log.warn("Exception thrown handling port injected event.", e);
1592 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001593 }
1594 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001595
1596 private class InternalPortStatsListener
1597 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1598 @Override
1599 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1600 if (event.type() == PUT) {
1601 Device device = devices.get(event.key());
1602 if (device != null) {
1603 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1604 }
1605 }
1606 }
1607 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001608}