blob: de6b523240563a3e001a76e7194740bbb217a5aa [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 HIGUCHI67a527f2014-10-02 22:23:54 -070019import com.google.common.collect.FluentIterable;
20import com.google.common.collect.ImmutableList;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -070021import com.google.common.collect.Maps;
22import com.google.common.collect.Sets;
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;
81import org.onosproject.store.service.WallclockClockManager;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070082import org.slf4j.Logger;
83
Madan Jampani47c93732014-10-06 20:46:08 -070084import java.io.IOException;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070085import java.util.ArrayList;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070086import java.util.Collection;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070087import java.util.Collections;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070088import java.util.HashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070089import java.util.HashSet;
90import java.util.Iterator;
91import java.util.List;
92import java.util.Map;
93import java.util.Map.Entry;
94import java.util.Objects;
95import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070096import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080097import java.util.concurrent.ExecutorService;
98import java.util.concurrent.Executors;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070099import java.util.concurrent.ScheduledExecutorService;
100import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700101
102import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700103import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700104import static com.google.common.base.Verify.verify;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800105import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
106import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800107import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800108import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800109import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
110import static org.onosproject.net.DefaultAnnotations.merge;
111import static org.onosproject.net.device.DeviceEvent.Type.*;
112import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
113import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700114import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800115import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700116
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700117/**
118 * Manages inventory of infrastructure devices using gossip protocol to distribute
119 * information.
120 */
121@Component(immediate = true)
122@Service
123public class GossipDeviceStore
124 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
125 implements DeviceStore {
126
127 private final Logger log = getLogger(getClass());
128
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700129 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800130 // Timeout in milliseconds to process device or ports on remote master node
131 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700132
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700133 // innerMap is used to lock a Device, thus instance should never be replaced.
134 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700135 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700136 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700137
138 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700139 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
140 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700141
142 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
143 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
144 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700145
146 // to be updated under Device lock
147 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
148 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700149
150 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700151 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700152
153 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700154 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700155
Madan Jampani47c93732014-10-06 20:46:08 -0700156 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700157 protected StorageService storageService;
158
159 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700160 protected ClusterCommunicationService clusterCommunicator;
161
Madan Jampani53e44e62014-10-07 12:39:51 -0700162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
163 protected ClusterService clusterService;
164
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
166 protected MastershipService mastershipService;
167
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800168 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
169 protected MastershipTermService termService;
170
171
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700172 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700173 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700174 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700175 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800176 .register(DistributedStoreSerializers.STORE_COMMON)
177 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
178 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
179 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700180 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800181 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
182 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700183 .register(DeviceAntiEntropyAdvertisement.class)
184 .register(DeviceFragmentId.class)
185 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800186 .register(DeviceInjectedEvent.class)
187 .register(PortInjectedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800188 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700189 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700190 };
191
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800192 private ExecutorService executor;
193
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800194 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700195
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800196 // TODO make these anti-entropy parameters configurable
197 private long initialDelaySec = 5;
198 private long periodSec = 5;
199
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700200 @Activate
201 public void activate() {
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800202 executor = Executors.newCachedThreadPool(groupedThreads("onos/device", "fg-%d"));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800203
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800204 backgroundExecutor =
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800205 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700206
Madan Jampani2af244a2015-02-22 13:12:01 -0800207 clusterCommunicator.addSubscriber(
208 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
209 clusterCommunicator.addSubscriber(
210 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
211 new InternalDeviceOfflineEventListener(),
212 executor);
213 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700214 new InternalRemoveRequestListener(),
215 executor);
Madan Jampani2af244a2015-02-22 13:12:01 -0800216 clusterCommunicator.addSubscriber(
217 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
218 clusterCommunicator.addSubscriber(
219 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
220 clusterCommunicator.addSubscriber(
221 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
222 clusterCommunicator.addSubscriber(
223 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
224 new InternalDeviceAdvertisementListener(),
225 backgroundExecutor);
226 clusterCommunicator.addSubscriber(
227 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
228 clusterCommunicator.addSubscriber(
229 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
230
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700231 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800232 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700233 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700234
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700235 // Create a distributed map for port stats.
236 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
237 .register(KryoNamespaces.API)
238 .register(DefaultPortStatistics.class)
239 .register(DeviceId.class)
240 .register(MultiValuedTimestamp.class)
241 .register(WallClockTimestamp.class);
242
243 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
244 .withName("port-stats")
245 .withSerializer(deviceDataSerializer)
246 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
247 .withClockService(new WallclockClockManager<>())
248 .withTombstonesDisabled()
249 .build();
250 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700251 log.info("Started");
252 }
253
254 @Deactivate
255 public void deactivate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700256
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800257 executor.shutdownNow();
258
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800259 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700260 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800261 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700262 log.error("Timeout during executor shutdown");
263 }
264 } catch (InterruptedException e) {
265 log.error("Error during executor shutdown", e);
266 }
267
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700268 deviceDescs.clear();
269 devices.clear();
270 devicePorts.clear();
271 availableDevices.clear();
272 log.info("Stopped");
273 }
274
275 @Override
276 public int getDeviceCount() {
277 return devices.size();
278 }
279
280 @Override
281 public Iterable<Device> getDevices() {
282 return Collections.unmodifiableCollection(devices.values());
283 }
284
285 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800286 public Iterable<Device> getAvailableDevices() {
287 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700288 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800289 }
290
291 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700292 public Device getDevice(DeviceId deviceId) {
293 return devices.get(deviceId);
294 }
295
296 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700297 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700298 DeviceId deviceId,
299 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800300 NodeId localNode = clusterService.getLocalNode().id();
301 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
302
303 // Process device update only if we're the master,
304 // otherwise signal the actual master.
305 DeviceEvent deviceEvent = null;
306 if (localNode.equals(deviceNode)) {
307
308 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
309 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
310 final Timestamped<DeviceDescription> mergedDesc;
311 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
312
313 synchronized (device) {
314 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
315 mergedDesc = device.get(providerId).getDeviceDesc();
316 }
317
318 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700319 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700320 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800321 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
322 }
323
324 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800325 // FIXME Temporary hack for NPE (ONOS-1171).
326 // Proper fix is to implement forwarding to master on ConfigProvider
327 // redo ONOS-490
328 if (deviceNode == null) {
329 // silently ignore
330 return null;
331 }
332
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800333
334 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
335 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800336
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800337 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700338 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800339 /* error log:
340 log.warn("Failed to process injected device id: {} desc: {} " +
341 "(cluster messaging failed: {})",
342 deviceId, deviceDescription, e);
343 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700344 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800345
346 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700347 }
348
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700349 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700350 DeviceId deviceId,
351 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700352
353 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800354 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700355 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700356
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800357 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700358 // locking per device
359
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700360 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
361 log.debug("Ignoring outdated event: {}", deltaDesc);
362 return null;
363 }
364
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800365 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700366
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700367 final Device oldDevice = devices.get(deviceId);
368 final Device newDevice;
369
370 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700371 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700372 // on new device or valid update
373 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800374 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700375 } else {
376 // outdated event, ignored.
377 return null;
378 }
379 if (oldDevice == null) {
380 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700381 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700382 } else {
383 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700384 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700385 }
386 }
387 }
388
389 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700390 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700391 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700392 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700393
394 // update composed device cache
395 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
396 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700397 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
398 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700399
400 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700401 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700402 }
403
404 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
405 }
406
407 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700408 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700409 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700410 Device oldDevice,
411 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700412 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700413 boolean propertiesChanged =
414 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700415 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
416 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700417 boolean annotationsChanged =
418 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700419
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700420 // Primary providers can respond to all changes, but ancillary ones
421 // should respond only to annotation changes.
422 if ((providerId.isAncillary() && annotationsChanged) ||
423 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700424 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
425 if (!replaced) {
426 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700427 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
428 providerId, oldDevice, devices.get(newDevice.id())
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700429 , newDevice);
430 }
431 if (!providerId.isAncillary()) {
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700432 boolean wasOnline = availableDevices.contains(newDevice.id());
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700433 markOnline(newDevice.id(), newTimestamp);
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700434 if (!wasOnline) {
435 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
436 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700437 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700438
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700439 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700440 }
441 return null;
442 }
443
444 @Override
445 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700446 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700447 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700448 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700449 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700450 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800451 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700452 }
453 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700454 }
455
456 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
457
458 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700459 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700460
461 // locking device
462 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700463
464 // accept off-line if given timestamp is newer than
465 // the latest Timestamp from Primary provider
466 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
467 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
468 if (timestamp.compareTo(lastTimestamp) <= 0) {
469 // outdated event ignore
470 return null;
471 }
472
473 offline.put(deviceId, timestamp);
474
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700475 Device device = devices.get(deviceId);
476 if (device == null) {
477 return null;
478 }
479 boolean removed = availableDevices.remove(deviceId);
480 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700481 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700482 }
483 return null;
484 }
485 }
486
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700487 /**
488 * Marks the device as available if the given timestamp is not outdated,
489 * compared to the time the device has been marked offline.
490 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700491 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700492 * @param timestamp of the event triggering this change.
493 * @return true if availability change request was accepted and changed the state
494 */
495 // Guarded by deviceDescs value (=Device lock)
496 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
497 // accept on-line if given timestamp is newer than
498 // the latest offline request Timestamp
499 Timestamp offlineTimestamp = offline.get(deviceId);
500 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700501 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700502
503 offline.remove(deviceId);
504 return availableDevices.add(deviceId);
505 }
506 return false;
507 }
508
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700509 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700510 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700511 DeviceId deviceId,
512 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700513
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800514 NodeId localNode = clusterService.getLocalNode().id();
515 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
516 // since it will trigger distributed store read.
517 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
518 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
519 // If we don't care much about topology performance, then it might be OK.
520 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700521
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800522 // Process port update only if we're the master of the device,
523 // otherwise signal the actual master.
524 List<DeviceEvent> deviceEvents = null;
525 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700526
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800527 final Timestamp newTimestamp;
528 try {
529 newTimestamp = deviceClockService.getTimestamp(deviceId);
530 } catch (IllegalStateException e) {
531 log.info("Timestamp was not available for device {}", deviceId);
532 log.debug(" discarding {}", portDescriptions);
533 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700534
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800535 // Possible situation:
536 // Device connected and became master for short period of time,
537 // but lost mastership before this instance had the chance to
538 // retrieve term information.
539
540 // Information dropped here is expected to be recoverable by
541 // device probing after mastership change
542
543 return Collections.emptyList();
544 }
545 log.debug("timestamp for {} {}", deviceId, newTimestamp);
546
547 final Timestamped<List<PortDescription>> timestampedInput
548 = new Timestamped<>(portDescriptions, newTimestamp);
549 final Timestamped<List<PortDescription>> merged;
550
551 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
552
553 synchronized (device) {
554 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
555 final DeviceDescriptions descs = device.get(providerId);
556 List<PortDescription> mergedList =
557 FluentIterable.from(portDescriptions)
558 .transform(new Function<PortDescription, PortDescription>() {
559 @Override
560 public PortDescription apply(PortDescription input) {
561 // lookup merged port description
562 return descs.getPortDesc(input.portNumber()).value();
563 }
564 }).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700565 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800566 }
567
568 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700569 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700570 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800571 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
572 }
573
574 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800575 // FIXME Temporary hack for NPE (ONOS-1171).
576 // Proper fix is to implement forwarding to master on ConfigProvider
577 // redo ONOS-490
578 if (deviceNode == null) {
579 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800580 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800581 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800582
583 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800584
585 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700586 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800587 /* error log:
588 log.warn("Failed to process injected ports of device id: {} " +
589 "(cluster messaging failed: {})",
590 deviceId, e);
591 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700592 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700593
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800594 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700595 }
596
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700597 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700598 DeviceId deviceId,
599 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700600
601 Device device = devices.get(deviceId);
602 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
603
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700604 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700605 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
606
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700607 List<DeviceEvent> events = new ArrayList<>();
608 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700609
610 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
611 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700612 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700613 }
614
615 DeviceDescriptions descs = descsMap.get(providerId);
616 // every provider must provide DeviceDescription.
617 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700618 "Device description for Device ID %s from Provider %s was not found",
619 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700620
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700621 Map<PortNumber, Port> ports = getPortMap(deviceId);
622
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700623 final Timestamp newTimestamp = portDescriptions.timestamp();
624
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700625 // Add new ports
626 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700627 for (PortDescription portDescription : portDescriptions.value()) {
628 final PortNumber number = portDescription.portNumber();
629 processed.add(number);
630
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700631 final Port oldPort = ports.get(number);
632 final Port newPort;
633
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700634
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700635 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
636 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700637 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700638 // on new port or valid update
639 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700640 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700641 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700642 newPort = composePort(device, number, descsMap);
643 } else {
644 // outdated event, ignored.
645 continue;
646 }
647
648 events.add(oldPort == null ?
649 createPort(device, newPort, ports) :
650 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700651 }
652
653 events.addAll(pruneOldPorts(device, ports, processed));
654 }
655 return FluentIterable.from(events).filter(notNull()).toList();
656 }
657
658 // Creates a new port based on the port description adds it to the map and
659 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700660 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700661 private DeviceEvent createPort(Device device, Port newPort,
662 Map<PortNumber, Port> ports) {
663 ports.put(newPort.number(), newPort);
664 return new DeviceEvent(PORT_ADDED, device, newPort);
665 }
666
667 // Checks if the specified port requires update and if so, it replaces the
668 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700669 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700670 private DeviceEvent updatePort(Device device, Port oldPort,
671 Port newPort,
672 Map<PortNumber, Port> ports) {
673 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700674 oldPort.type() != newPort.type() ||
675 oldPort.portSpeed() != newPort.portSpeed() ||
676 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700677 ports.put(oldPort.number(), newPort);
678 return new DeviceEvent(PORT_UPDATED, device, newPort);
679 }
680 return null;
681 }
682
683 // Prunes the specified list of ports based on which ports are in the
684 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700685 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700686 private List<DeviceEvent> pruneOldPorts(Device device,
687 Map<PortNumber, Port> ports,
688 Set<PortNumber> processed) {
689 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700690 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700691 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700692 Entry<PortNumber, Port> e = iterator.next();
693 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700694 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700695 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700696 iterator.remove();
697 }
698 }
699 return events;
700 }
701
702 // Gets the map of ports for the specified device; if one does not already
703 // exist, it creates and registers a new one.
704 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
705 return createIfAbsentUnchecked(devicePorts, deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700706 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700707 }
708
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700709 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700710 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700711 Map<ProviderId, DeviceDescriptions> r;
712 r = deviceDescs.get(deviceId);
713 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700714 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700715 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
716 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
717 if (concurrentlyAdded != null) {
718 r = concurrentlyAdded;
719 }
720 }
721 return r;
722 }
723
724 // Guarded by deviceDescs value (=Device lock)
725 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
726 Map<ProviderId, DeviceDescriptions> device,
727 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700728 synchronized (device) {
729 DeviceDescriptions r = device.get(providerId);
730 if (r == null) {
731 r = new DeviceDescriptions(deltaDesc);
732 device.put(providerId, r);
733 }
734 return r;
735 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700736 }
737
738 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700739 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
740 DeviceId deviceId,
741 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700742 final Timestamp newTimestamp;
743 try {
744 newTimestamp = deviceClockService.getTimestamp(deviceId);
745 } catch (IllegalStateException e) {
746 log.info("Timestamp was not available for device {}", deviceId);
747 log.debug(" discarding {}", portDescription);
748 // Failed to generate timestamp. Ignoring.
749 // See updatePorts comment
750 return null;
751 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700752 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700753 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700754 final DeviceEvent event;
755 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800756 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
757 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700758 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800759 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700760 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700761 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700762 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700763 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700764 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800765 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700766 }
767 return event;
768 }
769
770 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700771 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700772 Device device = devices.get(deviceId);
773 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
774
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700775 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700776 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
777
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700778 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700779
780 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
781 log.debug("Ignoring outdated event: {}", deltaDesc);
782 return null;
783 }
784
785 DeviceDescriptions descs = descsMap.get(providerId);
786 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700787 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700788 "Device description for Device ID %s from Provider %s was not found",
789 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700790
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700791 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
792 final PortNumber number = deltaDesc.value().portNumber();
793 final Port oldPort = ports.get(number);
794 final Port newPort;
795
796 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
797 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700798 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700799 // on new port or valid update
800 // update description
801 descs.putPortDesc(deltaDesc);
802 newPort = composePort(device, number, descsMap);
803 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700804 // same or outdated event, ignored.
805 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700806 return null;
807 }
808
809 if (oldPort == null) {
810 return createPort(device, newPort, ports);
811 } else {
812 return updatePort(device, oldPort, newPort, ports);
813 }
814 }
815 }
816
817 @Override
818 public List<Port> getPorts(DeviceId deviceId) {
819 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
820 if (ports == null) {
821 return Collections.emptyList();
822 }
823 return ImmutableList.copyOf(ports.values());
824 }
825
826 @Override
sangho538108b2015-04-08 14:29:20 -0700827 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
828 Collection<PortStatistics> portStats) {
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700829 Map<PortNumber, PortStatistics> statsMap = devicePortStats.get(deviceId);
sangho538108b2015-04-08 14:29:20 -0700830 if (statsMap == null) {
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700831 statsMap = Maps.newHashMap();
sangho538108b2015-04-08 14:29:20 -0700832 }
833
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700834 for (PortStatistics stat : portStats) {
sangho538108b2015-04-08 14:29:20 -0700835 PortNumber portNumber = PortNumber.portNumber(stat.port());
836 statsMap.put(portNumber, stat);
837 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700838 devicePortStats.put(deviceId, statsMap);
839 return null; // new DeviceEvent(PORT_STATS_UPDATED, devices.get(deviceId), null);
sangho538108b2015-04-08 14:29:20 -0700840 }
841
842 @Override
843 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700844 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
845 if (portStats == null) {
846 return Collections.emptyList();
847 }
848 return ImmutableList.copyOf(portStats.values());
849 }
850
851 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700852 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
853 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
854 return ports == null ? null : ports.get(portNumber);
855 }
856
857 @Override
858 public boolean isAvailable(DeviceId deviceId) {
859 return availableDevices.contains(deviceId);
860 }
861
862 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700863 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800864 final NodeId myId = clusterService.getLocalNode().id();
865 NodeId master = mastershipService.getMasterFor(deviceId);
866
867 // if there exist a master, forward
868 // if there is no master, try to become one and process
869
870 boolean relinquishAtEnd = false;
871 if (master == null) {
872 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
873 if (myRole != MastershipRole.NONE) {
874 relinquishAtEnd = true;
875 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800876 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800877 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800878 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700879 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800880 master = myId;
881 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700882 }
883
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800884 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800885 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700886 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800887
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800888 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700889 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800890 /* error log:
891 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
892 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800893
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800894 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700895 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800896 }
897
898 // I have control..
899
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700900 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700901 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700902 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800903 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700904 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800905 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700906 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800907 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800908 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800909 mastershipService.relinquishMastership(deviceId);
910 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700911 return event;
912 }
913
914 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
915 Timestamp timestamp) {
916
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700917 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700918 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700919 // accept removal request if given timestamp is newer than
920 // the latest Timestamp from Primary provider
921 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
922 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
923 if (timestamp.compareTo(lastTimestamp) <= 0) {
924 // outdated event ignore
925 return null;
926 }
927 removalRequest.put(deviceId, timestamp);
928
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700929 Device device = devices.remove(deviceId);
930 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700931 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
932 if (ports != null) {
933 ports.clear();
934 }
935 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700936 descs.clear();
937 return device == null ? null :
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700938 new DeviceEvent(DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700939 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700940 }
941
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700942 /**
943 * Checks if given timestamp is superseded by removal request
944 * with more recent timestamp.
945 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700946 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700947 * @param timestampToCheck timestamp of an event to check
948 * @return true if device is already removed
949 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700950 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
951 Timestamp removalTimestamp = removalRequest.get(deviceId);
952 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700953 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700954 // removalRequest is more recent
955 return true;
956 }
957 return false;
958 }
959
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700960 /**
961 * Returns a Device, merging description given from multiple Providers.
962 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700963 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700964 * @param providerDescs Collection of Descriptions from multiple providers
965 * @return Device instance
966 */
967 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700968 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700969
Thomas Vachuska444eda62014-10-28 13:09:42 -0700970 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700971
972 ProviderId primary = pickPrimaryPID(providerDescs);
973
974 DeviceDescriptions desc = providerDescs.get(primary);
975
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700976 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700977 Type type = base.type();
978 String manufacturer = base.manufacturer();
979 String hwVersion = base.hwVersion();
980 String swVersion = base.swVersion();
981 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700982 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700983 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
984 annotations = merge(annotations, base.annotations());
985
986 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
987 if (e.getKey().equals(primary)) {
988 continue;
989 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800990 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700991 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700992 // Currently assuming there will never be a key conflict between
993 // providers
994
995 // annotation merging. not so efficient, should revisit later
996 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
997 }
998
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700999 return new DefaultDevice(primary, deviceId, type, manufacturer,
1000 hwVersion, swVersion, serialNumber,
1001 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001002 }
1003
Marc De Leenheer88194c32015-05-29 22:10:59 -07001004 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1005 PortDescription description, Annotations annotations) {
1006 switch (description.type()) {
1007 case OMS:
1008 OmsPortDescription omsDesc = (OmsPortDescription) description;
1009 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1010 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1011 case OCH:
1012 OchPortDescription ochDesc = (OchPortDescription) description;
1013 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1014 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1015 case ODUCLT:
1016 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1017 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1018 default:
1019 return new DefaultPort(device, number, isEnabled, description.type(),
1020 description.portSpeed(), annotations);
1021 }
1022 }
1023
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001024 /**
1025 * Returns a Port, merging description given from multiple Providers.
1026 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001027 * @param device device the port is on
1028 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001029 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001030 * @return Port instance
1031 */
1032 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001033 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001034
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001035 ProviderId primary = pickPrimaryPID(descsMap);
1036 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001037 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001038 boolean isEnabled = false;
1039 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001040 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001041 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1042 if (portDesc != null) {
1043 isEnabled = portDesc.value().isEnabled();
1044 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001045 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001046 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001047 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001048 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001049 if (e.getKey().equals(primary)) {
1050 continue;
1051 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001052 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001053 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001054 // Currently assuming there will never be a key conflict between
1055 // providers
1056
1057 // annotation merging. not so efficient, should revisit later
1058 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1059 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001060 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1061 continue;
1062 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001063 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001064 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001065 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001066 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001067 }
1068 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001069 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001070 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001071 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001072 PortDescription current = portDesc.value();
1073 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001074 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001075 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001076 }
1077
1078 /**
1079 * @return primary ProviderID, or randomly chosen one if none exists
1080 */
1081 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001082 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001083 ProviderId fallBackPrimary = null;
1084 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1085 if (!e.getKey().isAncillary()) {
1086 return e.getKey();
1087 } else if (fallBackPrimary == null) {
1088 // pick randomly as a fallback in case there is no primary
1089 fallBackPrimary = e.getKey();
1090 }
1091 }
1092 return fallBackPrimary;
1093 }
1094
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001095 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001096 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001097 ProviderId pid = pickPrimaryPID(providerDescs);
1098 return providerDescs.get(pid);
1099 }
1100
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001101 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001102 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001103 }
1104
Jonathan Hart7d656f42015-01-27 14:07:23 -08001105 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001106 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001107 }
Madan Jampani47c93732014-10-06 20:46:08 -07001108
Jonathan Hart7d656f42015-01-27 14:07:23 -08001109 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001110 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001111 }
1112
Jonathan Hart7d656f42015-01-27 14:07:23 -08001113 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001114 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001115 }
1116
Jonathan Hart7d656f42015-01-27 14:07:23 -08001117 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001118 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001119 }
1120
Jonathan Hart7d656f42015-01-27 14:07:23 -08001121 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001122 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001123 }
1124
Jonathan Hart7d656f42015-01-27 14:07:23 -08001125 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001126 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1127 }
1128
1129 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1130 try {
1131 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1132 } catch (IOException e) {
1133 log.error("Failed to send" + event + " to " + recipient, e);
1134 }
1135 }
1136
1137 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1138 try {
1139 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1140 } catch (IOException e) {
1141 log.error("Failed to send" + event + " to " + recipient, e);
1142 }
1143 }
1144
1145 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1146 try {
1147 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1148 } catch (IOException e) {
1149 log.error("Failed to send" + event + " to " + recipient, e);
1150 }
1151 }
1152
1153 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1154 try {
1155 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1156 } catch (IOException e) {
1157 log.error("Failed to send" + event + " to " + recipient, e);
1158 }
1159 }
1160
1161 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1162 try {
1163 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1164 } catch (IOException e) {
1165 log.error("Failed to send" + event + " to " + recipient, e);
1166 }
1167 }
1168
1169 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1170 final NodeId self = clusterService.getLocalNode().id();
1171
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001172 final int numDevices = deviceDescs.size();
1173 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1174 final int portsPerDevice = 8; // random factor to minimize reallocation
1175 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1176 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001177
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001178 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001179
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001180 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001181 synchronized (devDescs) {
1182
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001183 // send device offline timestamp
1184 Timestamp lOffline = this.offline.get(deviceId);
1185 if (lOffline != null) {
1186 adOffline.put(deviceId, lOffline);
1187 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001188
1189 for (Entry<ProviderId, DeviceDescriptions>
1190 prov : devDescs.entrySet()) {
1191
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001192 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001193 final ProviderId provId = prov.getKey();
1194 final DeviceDescriptions descs = prov.getValue();
1195
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001196 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001197 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001198
1199 for (Entry<PortNumber, Timestamped<PortDescription>>
1200 portDesc : descs.getPortDescs().entrySet()) {
1201
1202 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001203 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001204 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001205 }
1206 }
1207 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001208 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001209
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001210 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001211 }
1212
1213 /**
1214 * Responds to anti-entropy advertisement message.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001215 * <p/>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001216 * Notify sender about out-dated information using regular replication message.
1217 * Send back advertisement to sender if not in sync.
1218 *
1219 * @param advertisement to respond to
1220 */
1221 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1222
1223 final NodeId sender = advertisement.sender();
1224
1225 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1226 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1227 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1228
1229 // Fragments to request
1230 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1231 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1232
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001233 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001234 final DeviceId deviceId = de.getKey();
1235 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1236
1237 synchronized (lDevice) {
1238 // latestTimestamp across provider
1239 // Note: can be null initially
1240 Timestamp localLatest = offline.get(deviceId);
1241
1242 // handle device Ads
1243 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1244 final ProviderId provId = prov.getKey();
1245 final DeviceDescriptions lDeviceDescs = prov.getValue();
1246
1247 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1248
1249
1250 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1251 Timestamp advDevTimestamp = devAds.get(devFragId);
1252
Jonathan Hart403ea932015-02-20 16:23:00 -08001253 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1254 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001255 // remote does not have it or outdated, suggest
1256 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1257 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1258 // local is outdated, request
1259 reqDevices.add(devFragId);
1260 }
1261
1262 // handle port Ads
1263 for (Entry<PortNumber, Timestamped<PortDescription>>
1264 pe : lDeviceDescs.getPortDescs().entrySet()) {
1265
1266 final PortNumber num = pe.getKey();
1267 final Timestamped<PortDescription> lPort = pe.getValue();
1268
1269 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1270
1271 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001272 if (advPortTimestamp == null || lPort.isNewerThan(
1273 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001274 // remote does not have it or outdated, suggest
1275 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1276 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1277 // local is outdated, request
1278 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1279 reqPorts.add(portFragId);
1280 }
1281
1282 // remove port Ad already processed
1283 portAds.remove(portFragId);
1284 } // end local port loop
1285
1286 // remove device Ad already processed
1287 devAds.remove(devFragId);
1288
1289 // find latest and update
1290 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1291 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001292 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001293 localLatest = providerLatest;
1294 }
1295 } // end local provider loop
1296
1297 // checking if remote timestamp is more recent.
1298 Timestamp rOffline = offlineAds.get(deviceId);
1299 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001300 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001301 // remote offline timestamp suggests that the
1302 // device is off-line
1303 markOfflineInternal(deviceId, rOffline);
1304 }
1305
1306 Timestamp lOffline = offline.get(deviceId);
1307 if (lOffline != null && rOffline == null) {
1308 // locally offline, but remote is online, suggest offline
1309 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1310 }
1311
1312 // remove device offline Ad already processed
1313 offlineAds.remove(deviceId);
1314 } // end local device loop
1315 } // device lock
1316
1317 // If there is any Ads left, request them
1318 log.trace("Ads left {}, {}", devAds, portAds);
1319 reqDevices.addAll(devAds.keySet());
1320 reqPorts.addAll(portAds.keySet());
1321
1322 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1323 log.trace("Nothing to request to remote peer {}", sender);
1324 return;
1325 }
1326
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001327 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001328
1329 // 2-way Anti-Entropy for now
1330 try {
1331 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1332 } catch (IOException e) {
1333 log.error("Failed to send response advertisement to " + sender, e);
1334 }
1335
1336// Sketch of 3-way Anti-Entropy
1337// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1338// ClusterMessage message = new ClusterMessage(
1339// clusterService.getLocalNode().id(),
1340// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1341// SERIALIZER.encode(request));
1342//
1343// try {
1344// clusterCommunicator.unicast(message, advertisement.sender());
1345// } catch (IOException e) {
1346// log.error("Failed to send advertisement reply to "
1347// + advertisement.sender(), e);
1348// }
Madan Jampani47c93732014-10-06 20:46:08 -07001349 }
1350
Madan Jampani255a58b2014-10-09 12:08:20 -07001351 private void notifyDelegateIfNotNull(DeviceEvent event) {
1352 if (event != null) {
1353 notifyDelegate(event);
1354 }
1355 }
1356
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001357 private final class SendAdvertisementTask implements Runnable {
1358
1359 @Override
1360 public void run() {
1361 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001362 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001363 return;
1364 }
1365
1366 try {
1367 final NodeId self = clusterService.getLocalNode().id();
1368 Set<ControllerNode> nodes = clusterService.getNodes();
1369
1370 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1371 .transform(toNodeId())
1372 .toList();
1373
1374 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001375 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001376 return;
1377 }
1378
1379 NodeId peer;
1380 do {
1381 int idx = RandomUtils.nextInt(0, nodeIds.size());
1382 peer = nodeIds.get(idx);
1383 } while (peer.equals(self));
1384
1385 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1386
1387 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001388 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001389 return;
1390 }
1391
1392 try {
1393 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1394 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001395 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001396 return;
1397 }
1398 } catch (Exception e) {
1399 // catch all Exception to avoid Scheduled task being suppressed.
1400 log.error("Exception thrown while sending advertisement", e);
1401 }
1402 }
1403 }
1404
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001405 private final class InternalDeviceEventListener
1406 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001407 @Override
1408 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001409 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001410 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001411
Madan Jampani47c93732014-10-06 20:46:08 -07001412 ProviderId providerId = event.providerId();
1413 DeviceId deviceId = event.deviceId();
1414 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001415
Madan Jampani2af244a2015-02-22 13:12:01 -08001416 try {
1417 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1418 } catch (Exception e) {
1419 log.warn("Exception thrown handling device update", e);
1420 }
Madan Jampani47c93732014-10-06 20:46:08 -07001421 }
1422 }
1423
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001424 private final class InternalDeviceOfflineEventListener
1425 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001426 @Override
1427 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001428 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001429 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001430
1431 DeviceId deviceId = event.deviceId();
1432 Timestamp timestamp = event.timestamp();
1433
Madan Jampani2af244a2015-02-22 13:12:01 -08001434 try {
1435 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1436 } catch (Exception e) {
1437 log.warn("Exception thrown handling device offline", e);
1438 }
Madan Jampani25322532014-10-08 11:20:38 -07001439 }
1440 }
1441
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001442 private final class InternalRemoveRequestListener
1443 implements ClusterMessageHandler {
1444 @Override
1445 public void handle(ClusterMessage message) {
1446 log.debug("Received device remove request from peer: {}", message.sender());
1447 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001448
Madan Jampani2af244a2015-02-22 13:12:01 -08001449 try {
1450 removeDevice(did);
1451 } catch (Exception e) {
1452 log.warn("Exception thrown handling device remove", e);
1453 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001454 }
1455 }
1456
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001457 private final class InternalDeviceRemovedEventListener
1458 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001459 @Override
1460 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001461 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001462 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001463
1464 DeviceId deviceId = event.deviceId();
1465 Timestamp timestamp = event.timestamp();
1466
Madan Jampani2af244a2015-02-22 13:12:01 -08001467 try {
1468 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1469 } catch (Exception e) {
1470 log.warn("Exception thrown handling device removed", e);
1471 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001472 }
1473 }
1474
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001475 private final class InternalPortEventListener
1476 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001477 @Override
1478 public void handle(ClusterMessage message) {
1479
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001480 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001481 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001482
1483 ProviderId providerId = event.providerId();
1484 DeviceId deviceId = event.deviceId();
1485 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1486
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001487 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001488 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001489 // Note: dropped information will be recovered by anti-entropy
1490 return;
1491 }
1492
Madan Jampani2af244a2015-02-22 13:12:01 -08001493 try {
1494 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1495 } catch (Exception e) {
1496 log.warn("Exception thrown handling port update", e);
1497 }
Madan Jampani47c93732014-10-06 20:46:08 -07001498 }
1499 }
1500
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001501 private final class InternalPortStatusEventListener
1502 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001503 @Override
1504 public void handle(ClusterMessage message) {
1505
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001506 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001507 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001508
1509 ProviderId providerId = event.providerId();
1510 DeviceId deviceId = event.deviceId();
1511 Timestamped<PortDescription> portDescription = event.portDescription();
1512
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001513 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001514 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001515 // Note: dropped information will be recovered by anti-entropy
1516 return;
1517 }
1518
Madan Jampani2af244a2015-02-22 13:12:01 -08001519 try {
1520 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1521 } catch (Exception e) {
1522 log.warn("Exception thrown handling port update", e);
1523 }
Madan Jampani47c93732014-10-06 20:46:08 -07001524 }
1525 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001526
1527 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001528 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001529 @Override
1530 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001531 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001532 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001533 try {
1534 handleAdvertisement(advertisement);
1535 } catch (Exception e) {
1536 log.warn("Exception thrown handling Device advertisements.", e);
1537 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001538 }
1539 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001540
1541 private final class DeviceInjectedEventListener
1542 implements ClusterMessageHandler {
1543 @Override
1544 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001545 log.debug("Received injected device event from peer: {}", message.sender());
1546 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1547
1548 ProviderId providerId = event.providerId();
1549 DeviceId deviceId = event.deviceId();
1550 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001551 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1552 // workaround for ONOS-1208
1553 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1554 return;
1555 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001556
Madan Jampani2af244a2015-02-22 13:12:01 -08001557 try {
1558 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1559 } catch (Exception e) {
1560 log.warn("Exception thrown handling device injected event.", e);
1561 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001562 }
1563 }
1564
1565 private final class PortInjectedEventListener
1566 implements ClusterMessageHandler {
1567 @Override
1568 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001569 log.debug("Received injected port event from peer: {}", message.sender());
1570 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1571
1572 ProviderId providerId = event.providerId();
1573 DeviceId deviceId = event.deviceId();
1574 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001575 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1576 // workaround for ONOS-1208
1577 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1578 return;
1579 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001580
Madan Jampani2af244a2015-02-22 13:12:01 -08001581 try {
1582 updatePorts(providerId, deviceId, portDescriptions);
1583 } catch (Exception e) {
1584 log.warn("Exception thrown handling port injected event.", e);
1585 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001586 }
1587 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001588
1589 private class InternalPortStatsListener
1590 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1591 @Override
1592 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1593 if (event.type() == PUT) {
1594 Device device = devices.get(event.key());
1595 if (device != null) {
1596 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1597 }
1598 }
1599 }
1600 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001601}