blob: 3d106c9a72b8e285c8b7b84827e8ddd0f9af94fb [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;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070081import org.slf4j.Logger;
82
Madan Jampani47c93732014-10-06 20:46:08 -070083import java.io.IOException;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070084import java.util.ArrayList;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070085import java.util.Collection;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070086import java.util.Collections;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070087import java.util.HashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070088import java.util.HashSet;
89import java.util.Iterator;
90import java.util.List;
91import java.util.Map;
92import java.util.Map.Entry;
93import java.util.Objects;
94import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070095import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080096import java.util.concurrent.ExecutorService;
97import java.util.concurrent.Executors;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070098import java.util.concurrent.ScheduledExecutorService;
99import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700100
101import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700102import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700103import static com.google.common.base.Verify.verify;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800104import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
105import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800106import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800107import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800108import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
109import static org.onosproject.net.DefaultAnnotations.merge;
110import static org.onosproject.net.device.DeviceEvent.Type.*;
111import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
112import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700113import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800114import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700115
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700116/**
117 * Manages inventory of infrastructure devices using gossip protocol to distribute
118 * information.
119 */
120@Component(immediate = true)
121@Service
122public class GossipDeviceStore
123 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
124 implements DeviceStore {
125
126 private final Logger log = getLogger(getClass());
127
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700128 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800129 // Timeout in milliseconds to process device or ports on remote master node
130 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700131
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700132 // innerMap is used to lock a Device, thus instance should never be replaced.
133 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700134 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700135 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700136
137 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700138 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
139 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700140
141 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
142 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
143 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700144
145 // to be updated under Device lock
146 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
147 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700148
149 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700150 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700151
152 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700153 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700154
Madan Jampani47c93732014-10-06 20:46:08 -0700155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700156 protected StorageService storageService;
157
158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700159 protected ClusterCommunicationService clusterCommunicator;
160
Madan Jampani53e44e62014-10-07 12:39:51 -0700161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
162 protected ClusterService clusterService;
163
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
165 protected MastershipService mastershipService;
166
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
168 protected MastershipTermService termService;
169
170
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700171 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700172 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700173 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700174 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800175 .register(DistributedStoreSerializers.STORE_COMMON)
176 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
177 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
178 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700179 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800180 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
181 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700182 .register(DeviceAntiEntropyAdvertisement.class)
183 .register(DeviceFragmentId.class)
184 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800185 .register(DeviceInjectedEvent.class)
186 .register(PortInjectedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800187 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700188 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700189 };
190
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800191 private ExecutorService executor;
192
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800193 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700194
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800195 // TODO make these anti-entropy parameters configurable
196 private long initialDelaySec = 5;
197 private long periodSec = 5;
198
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700199 @Activate
200 public void activate() {
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800201 executor = Executors.newCachedThreadPool(groupedThreads("onos/device", "fg-%d"));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800202
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800203 backgroundExecutor =
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800204 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700205
Madan Jampani2af244a2015-02-22 13:12:01 -0800206 clusterCommunicator.addSubscriber(
207 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
208 clusterCommunicator.addSubscriber(
209 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
210 new InternalDeviceOfflineEventListener(),
211 executor);
212 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700213 new InternalRemoveRequestListener(),
214 executor);
Madan Jampani2af244a2015-02-22 13:12:01 -0800215 clusterCommunicator.addSubscriber(
216 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
217 clusterCommunicator.addSubscriber(
218 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
219 clusterCommunicator.addSubscriber(
220 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
221 clusterCommunicator.addSubscriber(
222 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
223 new InternalDeviceAdvertisementListener(),
224 backgroundExecutor);
225 clusterCommunicator.addSubscriber(
226 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
227 clusterCommunicator.addSubscriber(
228 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
229
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700230 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800231 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700232 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700233
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700234 // Create a distributed map for port stats.
235 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
236 .register(KryoNamespaces.API)
237 .register(DefaultPortStatistics.class)
238 .register(DeviceId.class)
239 .register(MultiValuedTimestamp.class)
240 .register(WallClockTimestamp.class);
241
242 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
243 .withName("port-stats")
244 .withSerializer(deviceDataSerializer)
245 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700246 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700247 .withTombstonesDisabled()
248 .build();
249 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700250 log.info("Started");
251 }
252
253 @Deactivate
254 public void deactivate() {
Madan Jampani632f16b2015-08-11 12:42:59 -0700255 devicePortStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800256 executor.shutdownNow();
257
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800258 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700259 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800260 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700261 log.error("Timeout during executor shutdown");
262 }
263 } catch (InterruptedException e) {
264 log.error("Error during executor shutdown", e);
265 }
266
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700267 deviceDescs.clear();
268 devices.clear();
269 devicePorts.clear();
270 availableDevices.clear();
271 log.info("Stopped");
272 }
273
274 @Override
275 public int getDeviceCount() {
276 return devices.size();
277 }
278
279 @Override
280 public Iterable<Device> getDevices() {
281 return Collections.unmodifiableCollection(devices.values());
282 }
283
284 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800285 public Iterable<Device> getAvailableDevices() {
286 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700287 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800288 }
289
290 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700291 public Device getDevice(DeviceId deviceId) {
292 return devices.get(deviceId);
293 }
294
295 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700296 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700297 DeviceId deviceId,
298 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800299 NodeId localNode = clusterService.getLocalNode().id();
300 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
301
302 // Process device update only if we're the master,
303 // otherwise signal the actual master.
304 DeviceEvent deviceEvent = null;
305 if (localNode.equals(deviceNode)) {
306
307 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
308 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
309 final Timestamped<DeviceDescription> mergedDesc;
310 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
311
312 synchronized (device) {
313 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
314 mergedDesc = device.get(providerId).getDeviceDesc();
315 }
316
317 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700318 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700319 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800320 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
321 }
322
323 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800324 // FIXME Temporary hack for NPE (ONOS-1171).
325 // Proper fix is to implement forwarding to master on ConfigProvider
326 // redo ONOS-490
327 if (deviceNode == null) {
328 // silently ignore
329 return null;
330 }
331
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800332
333 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
334 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800335
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800336 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700337 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800338 /* error log:
339 log.warn("Failed to process injected device id: {} desc: {} " +
340 "(cluster messaging failed: {})",
341 deviceId, deviceDescription, e);
342 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700343 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800344
345 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700346 }
347
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700348 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700349 DeviceId deviceId,
350 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700351
352 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800353 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700354 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700355
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800356 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700357 // locking per device
358
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700359 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
360 log.debug("Ignoring outdated event: {}", deltaDesc);
361 return null;
362 }
363
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800364 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700365
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700366 final Device oldDevice = devices.get(deviceId);
367 final Device newDevice;
368
369 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700370 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700371 // on new device or valid update
372 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800373 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700374 } else {
375 // outdated event, ignored.
376 return null;
377 }
378 if (oldDevice == null) {
379 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700380 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700381 } else {
382 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700383 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700384 }
385 }
386 }
387
388 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700389 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700390 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700391 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700392
393 // update composed device cache
394 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
395 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700396 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
397 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700398
399 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700400 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700401 }
402
403 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
404 }
405
406 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700407 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700408 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700409 Device oldDevice,
410 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700411 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700412 boolean propertiesChanged =
413 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700414 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
415 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700416 boolean annotationsChanged =
417 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700418
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700419 // Primary providers can respond to all changes, but ancillary ones
420 // should respond only to annotation changes.
421 if ((providerId.isAncillary() && annotationsChanged) ||
422 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700423 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
424 if (!replaced) {
425 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700426 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
427 providerId, oldDevice, devices.get(newDevice.id())
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700428 , newDevice);
429 }
430 if (!providerId.isAncillary()) {
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700431 boolean wasOnline = availableDevices.contains(newDevice.id());
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700432 markOnline(newDevice.id(), newTimestamp);
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700433 if (!wasOnline) {
434 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
435 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700436 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700437
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700438 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700439 }
440 return null;
441 }
442
443 @Override
444 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700445 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700446 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700447 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700448 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700449 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800450 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700451 }
452 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700453 }
454
455 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
456
457 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700458 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700459
460 // locking device
461 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700462
463 // accept off-line if given timestamp is newer than
464 // the latest Timestamp from Primary provider
465 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
466 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
467 if (timestamp.compareTo(lastTimestamp) <= 0) {
468 // outdated event ignore
469 return null;
470 }
471
472 offline.put(deviceId, timestamp);
473
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700474 Device device = devices.get(deviceId);
475 if (device == null) {
476 return null;
477 }
478 boolean removed = availableDevices.remove(deviceId);
479 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700480 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700481 }
482 return null;
483 }
484 }
485
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700486 /**
487 * Marks the device as available if the given timestamp is not outdated,
488 * compared to the time the device has been marked offline.
489 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700490 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700491 * @param timestamp of the event triggering this change.
492 * @return true if availability change request was accepted and changed the state
493 */
494 // Guarded by deviceDescs value (=Device lock)
495 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
496 // accept on-line if given timestamp is newer than
497 // the latest offline request Timestamp
498 Timestamp offlineTimestamp = offline.get(deviceId);
499 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700500 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700501
502 offline.remove(deviceId);
503 return availableDevices.add(deviceId);
504 }
505 return false;
506 }
507
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700508 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700509 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700510 DeviceId deviceId,
511 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700512
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800513 NodeId localNode = clusterService.getLocalNode().id();
514 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
515 // since it will trigger distributed store read.
516 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
517 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
518 // If we don't care much about topology performance, then it might be OK.
519 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700520
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800521 // Process port update only if we're the master of the device,
522 // otherwise signal the actual master.
523 List<DeviceEvent> deviceEvents = null;
524 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700525
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800526 final Timestamp newTimestamp;
527 try {
528 newTimestamp = deviceClockService.getTimestamp(deviceId);
529 } catch (IllegalStateException e) {
530 log.info("Timestamp was not available for device {}", deviceId);
531 log.debug(" discarding {}", portDescriptions);
532 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700533
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800534 // Possible situation:
535 // Device connected and became master for short period of time,
536 // but lost mastership before this instance had the chance to
537 // retrieve term information.
538
539 // Information dropped here is expected to be recoverable by
540 // device probing after mastership change
541
542 return Collections.emptyList();
543 }
544 log.debug("timestamp for {} {}", deviceId, newTimestamp);
545
546 final Timestamped<List<PortDescription>> timestampedInput
547 = new Timestamped<>(portDescriptions, newTimestamp);
548 final Timestamped<List<PortDescription>> merged;
549
550 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
551
552 synchronized (device) {
553 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
554 final DeviceDescriptions descs = device.get(providerId);
555 List<PortDescription> mergedList =
556 FluentIterable.from(portDescriptions)
557 .transform(new Function<PortDescription, PortDescription>() {
558 @Override
559 public PortDescription apply(PortDescription input) {
560 // lookup merged port description
561 return descs.getPortDesc(input.portNumber()).value();
562 }
563 }).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700564 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800565 }
566
567 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700568 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700569 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800570 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
571 }
572
573 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800574 // FIXME Temporary hack for NPE (ONOS-1171).
575 // Proper fix is to implement forwarding to master on ConfigProvider
576 // redo ONOS-490
577 if (deviceNode == null) {
578 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800579 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800580 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800581
582 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800583
584 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700585 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800586 /* error log:
587 log.warn("Failed to process injected ports of device id: {} " +
588 "(cluster messaging failed: {})",
589 deviceId, e);
590 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700591 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700592
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800593 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700594 }
595
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700596 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700597 DeviceId deviceId,
598 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700599
600 Device device = devices.get(deviceId);
601 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
602
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700603 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700604 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
605
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700606 List<DeviceEvent> events = new ArrayList<>();
607 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700608
609 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
610 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700611 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700612 }
613
614 DeviceDescriptions descs = descsMap.get(providerId);
615 // every provider must provide DeviceDescription.
616 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700617 "Device description for Device ID %s from Provider %s was not found",
618 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700619
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700620 Map<PortNumber, Port> ports = getPortMap(deviceId);
621
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700622 final Timestamp newTimestamp = portDescriptions.timestamp();
623
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700624 // Add new ports
625 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700626 for (PortDescription portDescription : portDescriptions.value()) {
627 final PortNumber number = portDescription.portNumber();
628 processed.add(number);
629
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700630 final Port oldPort = ports.get(number);
631 final Port newPort;
632
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700633
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700634 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
635 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700636 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700637 // on new port or valid update
638 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700639 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700640 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700641 newPort = composePort(device, number, descsMap);
642 } else {
643 // outdated event, ignored.
644 continue;
645 }
646
647 events.add(oldPort == null ?
648 createPort(device, newPort, ports) :
649 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700650 }
651
652 events.addAll(pruneOldPorts(device, ports, processed));
653 }
654 return FluentIterable.from(events).filter(notNull()).toList();
655 }
656
657 // Creates a new port based on the port description adds it to the map and
658 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700659 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700660 private DeviceEvent createPort(Device device, Port newPort,
661 Map<PortNumber, Port> ports) {
662 ports.put(newPort.number(), newPort);
663 return new DeviceEvent(PORT_ADDED, device, newPort);
664 }
665
666 // Checks if the specified port requires update and if so, it replaces the
667 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700668 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700669 private DeviceEvent updatePort(Device device, Port oldPort,
670 Port newPort,
671 Map<PortNumber, Port> ports) {
672 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700673 oldPort.type() != newPort.type() ||
674 oldPort.portSpeed() != newPort.portSpeed() ||
675 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700676 ports.put(oldPort.number(), newPort);
677 return new DeviceEvent(PORT_UPDATED, device, newPort);
678 }
679 return null;
680 }
681
682 // Prunes the specified list of ports based on which ports are in the
683 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700684 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700685 private List<DeviceEvent> pruneOldPorts(Device device,
686 Map<PortNumber, Port> ports,
687 Set<PortNumber> processed) {
688 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700689 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700690 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700691 Entry<PortNumber, Port> e = iterator.next();
692 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700693 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700694 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700695 iterator.remove();
696 }
697 }
698 return events;
699 }
700
701 // Gets the map of ports for the specified device; if one does not already
702 // exist, it creates and registers a new one.
703 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
704 return createIfAbsentUnchecked(devicePorts, deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700705 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700706 }
707
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700708 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700709 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700710 Map<ProviderId, DeviceDescriptions> r;
711 r = deviceDescs.get(deviceId);
712 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700713 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700714 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
715 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
716 if (concurrentlyAdded != null) {
717 r = concurrentlyAdded;
718 }
719 }
720 return r;
721 }
722
723 // Guarded by deviceDescs value (=Device lock)
724 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
725 Map<ProviderId, DeviceDescriptions> device,
726 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700727 synchronized (device) {
728 DeviceDescriptions r = device.get(providerId);
729 if (r == null) {
730 r = new DeviceDescriptions(deltaDesc);
731 device.put(providerId, r);
732 }
733 return r;
734 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700735 }
736
737 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700738 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
739 DeviceId deviceId,
740 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700741 final Timestamp newTimestamp;
742 try {
743 newTimestamp = deviceClockService.getTimestamp(deviceId);
744 } catch (IllegalStateException e) {
745 log.info("Timestamp was not available for device {}", deviceId);
746 log.debug(" discarding {}", portDescription);
747 // Failed to generate timestamp. Ignoring.
748 // See updatePorts comment
749 return null;
750 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700751 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700752 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700753 final DeviceEvent event;
754 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800755 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
756 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700757 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800758 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700759 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700760 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700761 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700762 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700763 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800764 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700765 }
766 return event;
767 }
768
769 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700770 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700771 Device device = devices.get(deviceId);
772 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
773
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700774 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700775 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
776
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700777 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700778
779 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
780 log.debug("Ignoring outdated event: {}", deltaDesc);
781 return null;
782 }
783
784 DeviceDescriptions descs = descsMap.get(providerId);
785 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700786 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700787 "Device description for Device ID %s from Provider %s was not found",
788 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700789
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700790 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
791 final PortNumber number = deltaDesc.value().portNumber();
792 final Port oldPort = ports.get(number);
793 final Port newPort;
794
795 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
796 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700797 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700798 // on new port or valid update
799 // update description
800 descs.putPortDesc(deltaDesc);
801 newPort = composePort(device, number, descsMap);
802 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700803 // same or outdated event, ignored.
804 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700805 return null;
806 }
807
808 if (oldPort == null) {
809 return createPort(device, newPort, ports);
810 } else {
811 return updatePort(device, oldPort, newPort, ports);
812 }
813 }
814 }
815
816 @Override
817 public List<Port> getPorts(DeviceId deviceId) {
818 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
819 if (ports == null) {
820 return Collections.emptyList();
821 }
822 return ImmutableList.copyOf(ports.values());
823 }
824
825 @Override
sangho538108b2015-04-08 14:29:20 -0700826 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
827 Collection<PortStatistics> portStats) {
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700828 Map<PortNumber, PortStatistics> statsMap = devicePortStats.get(deviceId);
sangho538108b2015-04-08 14:29:20 -0700829 if (statsMap == null) {
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700830 statsMap = Maps.newHashMap();
sangho538108b2015-04-08 14:29:20 -0700831 }
832
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700833 for (PortStatistics stat : portStats) {
sangho538108b2015-04-08 14:29:20 -0700834 PortNumber portNumber = PortNumber.portNumber(stat.port());
835 statsMap.put(portNumber, stat);
836 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700837 devicePortStats.put(deviceId, statsMap);
838 return null; // new DeviceEvent(PORT_STATS_UPDATED, devices.get(deviceId), null);
sangho538108b2015-04-08 14:29:20 -0700839 }
840
841 @Override
842 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700843 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
844 if (portStats == null) {
845 return Collections.emptyList();
846 }
847 return ImmutableList.copyOf(portStats.values());
848 }
849
850 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700851 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
852 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
853 return ports == null ? null : ports.get(portNumber);
854 }
855
856 @Override
857 public boolean isAvailable(DeviceId deviceId) {
858 return availableDevices.contains(deviceId);
859 }
860
861 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700862 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800863 final NodeId myId = clusterService.getLocalNode().id();
864 NodeId master = mastershipService.getMasterFor(deviceId);
865
866 // if there exist a master, forward
867 // if there is no master, try to become one and process
868
869 boolean relinquishAtEnd = false;
870 if (master == null) {
871 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
872 if (myRole != MastershipRole.NONE) {
873 relinquishAtEnd = true;
874 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800875 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800876 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800877 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700878 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800879 master = myId;
880 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700881 }
882
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800883 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800884 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700885 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800886
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800887 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700888 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800889 /* error log:
890 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
891 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800892
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800893 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700894 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800895 }
896
897 // I have control..
898
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700899 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700900 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700901 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800902 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700903 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800904 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700905 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800906 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800907 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800908 mastershipService.relinquishMastership(deviceId);
909 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700910 return event;
911 }
912
913 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
914 Timestamp timestamp) {
915
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700916 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700917 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700918 // accept removal request if given timestamp is newer than
919 // the latest Timestamp from Primary provider
920 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
921 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
922 if (timestamp.compareTo(lastTimestamp) <= 0) {
923 // outdated event ignore
924 return null;
925 }
926 removalRequest.put(deviceId, timestamp);
927
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700928 Device device = devices.remove(deviceId);
929 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700930 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
931 if (ports != null) {
932 ports.clear();
933 }
934 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700935 descs.clear();
936 return device == null ? null :
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700937 new DeviceEvent(DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700938 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700939 }
940
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700941 /**
942 * Checks if given timestamp is superseded by removal request
943 * with more recent timestamp.
944 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700945 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700946 * @param timestampToCheck timestamp of an event to check
947 * @return true if device is already removed
948 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700949 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
950 Timestamp removalTimestamp = removalRequest.get(deviceId);
951 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700952 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700953 // removalRequest is more recent
954 return true;
955 }
956 return false;
957 }
958
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700959 /**
960 * Returns a Device, merging description given from multiple Providers.
961 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700962 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700963 * @param providerDescs Collection of Descriptions from multiple providers
964 * @return Device instance
965 */
966 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700967 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700968
Thomas Vachuska444eda62014-10-28 13:09:42 -0700969 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700970
971 ProviderId primary = pickPrimaryPID(providerDescs);
972
973 DeviceDescriptions desc = providerDescs.get(primary);
974
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700975 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700976 Type type = base.type();
977 String manufacturer = base.manufacturer();
978 String hwVersion = base.hwVersion();
979 String swVersion = base.swVersion();
980 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700981 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700982 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
983 annotations = merge(annotations, base.annotations());
984
985 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
986 if (e.getKey().equals(primary)) {
987 continue;
988 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800989 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700990 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700991 // Currently assuming there will never be a key conflict between
992 // providers
993
994 // annotation merging. not so efficient, should revisit later
995 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
996 }
997
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700998 return new DefaultDevice(primary, deviceId, type, manufacturer,
999 hwVersion, swVersion, serialNumber,
1000 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001001 }
1002
Marc De Leenheer88194c32015-05-29 22:10:59 -07001003 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1004 PortDescription description, Annotations annotations) {
1005 switch (description.type()) {
1006 case OMS:
1007 OmsPortDescription omsDesc = (OmsPortDescription) description;
1008 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1009 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1010 case OCH:
1011 OchPortDescription ochDesc = (OchPortDescription) description;
1012 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1013 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1014 case ODUCLT:
1015 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1016 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1017 default:
1018 return new DefaultPort(device, number, isEnabled, description.type(),
1019 description.portSpeed(), annotations);
1020 }
1021 }
1022
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001023 /**
1024 * Returns a Port, merging description given from multiple Providers.
1025 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001026 * @param device device the port is on
1027 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001028 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001029 * @return Port instance
1030 */
1031 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001032 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001033
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001034 ProviderId primary = pickPrimaryPID(descsMap);
1035 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001036 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001037 boolean isEnabled = false;
1038 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001039 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001040 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1041 if (portDesc != null) {
1042 isEnabled = portDesc.value().isEnabled();
1043 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001044 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001045 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001046 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001047 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001048 if (e.getKey().equals(primary)) {
1049 continue;
1050 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001051 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001052 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001053 // Currently assuming there will never be a key conflict between
1054 // providers
1055
1056 // annotation merging. not so efficient, should revisit later
1057 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1058 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001059 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1060 continue;
1061 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001062 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001063 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001064 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001065 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001066 }
1067 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001068 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001069 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001070 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001071 PortDescription current = portDesc.value();
1072 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001073 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001074 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001075 }
1076
1077 /**
1078 * @return primary ProviderID, or randomly chosen one if none exists
1079 */
1080 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001081 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001082 ProviderId fallBackPrimary = null;
1083 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1084 if (!e.getKey().isAncillary()) {
1085 return e.getKey();
1086 } else if (fallBackPrimary == null) {
1087 // pick randomly as a fallback in case there is no primary
1088 fallBackPrimary = e.getKey();
1089 }
1090 }
1091 return fallBackPrimary;
1092 }
1093
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001094 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001095 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001096 ProviderId pid = pickPrimaryPID(providerDescs);
1097 return providerDescs.get(pid);
1098 }
1099
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001100 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001101 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001102 }
1103
Jonathan Hart7d656f42015-01-27 14:07:23 -08001104 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001105 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001106 }
Madan Jampani47c93732014-10-06 20:46:08 -07001107
Jonathan Hart7d656f42015-01-27 14:07:23 -08001108 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001109 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001110 }
1111
Jonathan Hart7d656f42015-01-27 14:07:23 -08001112 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001113 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001114 }
1115
Jonathan Hart7d656f42015-01-27 14:07:23 -08001116 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001117 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001118 }
1119
Jonathan Hart7d656f42015-01-27 14:07:23 -08001120 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001121 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001122 }
1123
Jonathan Hart7d656f42015-01-27 14:07:23 -08001124 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001125 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1126 }
1127
1128 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1129 try {
1130 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1131 } catch (IOException e) {
1132 log.error("Failed to send" + event + " to " + recipient, e);
1133 }
1134 }
1135
1136 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1137 try {
1138 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1139 } catch (IOException e) {
1140 log.error("Failed to send" + event + " to " + recipient, e);
1141 }
1142 }
1143
1144 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1145 try {
1146 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1147 } catch (IOException e) {
1148 log.error("Failed to send" + event + " to " + recipient, e);
1149 }
1150 }
1151
1152 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1153 try {
1154 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1155 } catch (IOException e) {
1156 log.error("Failed to send" + event + " to " + recipient, e);
1157 }
1158 }
1159
1160 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1161 try {
1162 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1163 } catch (IOException e) {
1164 log.error("Failed to send" + event + " to " + recipient, e);
1165 }
1166 }
1167
1168 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1169 final NodeId self = clusterService.getLocalNode().id();
1170
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001171 final int numDevices = deviceDescs.size();
1172 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1173 final int portsPerDevice = 8; // random factor to minimize reallocation
1174 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1175 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001176
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001177 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001178
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001179 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001180 synchronized (devDescs) {
1181
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001182 // send device offline timestamp
1183 Timestamp lOffline = this.offline.get(deviceId);
1184 if (lOffline != null) {
1185 adOffline.put(deviceId, lOffline);
1186 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001187
1188 for (Entry<ProviderId, DeviceDescriptions>
1189 prov : devDescs.entrySet()) {
1190
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001191 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001192 final ProviderId provId = prov.getKey();
1193 final DeviceDescriptions descs = prov.getValue();
1194
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001195 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001196 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001197
1198 for (Entry<PortNumber, Timestamped<PortDescription>>
1199 portDesc : descs.getPortDescs().entrySet()) {
1200
1201 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001202 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001203 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001204 }
1205 }
1206 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001207 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001208
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001209 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001210 }
1211
1212 /**
1213 * Responds to anti-entropy advertisement message.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001214 * <p/>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001215 * Notify sender about out-dated information using regular replication message.
1216 * Send back advertisement to sender if not in sync.
1217 *
1218 * @param advertisement to respond to
1219 */
1220 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1221
1222 final NodeId sender = advertisement.sender();
1223
1224 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1225 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1226 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1227
1228 // Fragments to request
1229 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1230 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1231
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001232 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001233 final DeviceId deviceId = de.getKey();
1234 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1235
1236 synchronized (lDevice) {
1237 // latestTimestamp across provider
1238 // Note: can be null initially
1239 Timestamp localLatest = offline.get(deviceId);
1240
1241 // handle device Ads
1242 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1243 final ProviderId provId = prov.getKey();
1244 final DeviceDescriptions lDeviceDescs = prov.getValue();
1245
1246 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1247
1248
1249 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1250 Timestamp advDevTimestamp = devAds.get(devFragId);
1251
Jonathan Hart403ea932015-02-20 16:23:00 -08001252 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1253 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001254 // remote does not have it or outdated, suggest
1255 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1256 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1257 // local is outdated, request
1258 reqDevices.add(devFragId);
1259 }
1260
1261 // handle port Ads
1262 for (Entry<PortNumber, Timestamped<PortDescription>>
1263 pe : lDeviceDescs.getPortDescs().entrySet()) {
1264
1265 final PortNumber num = pe.getKey();
1266 final Timestamped<PortDescription> lPort = pe.getValue();
1267
1268 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1269
1270 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001271 if (advPortTimestamp == null || lPort.isNewerThan(
1272 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001273 // remote does not have it or outdated, suggest
1274 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1275 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1276 // local is outdated, request
1277 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1278 reqPorts.add(portFragId);
1279 }
1280
1281 // remove port Ad already processed
1282 portAds.remove(portFragId);
1283 } // end local port loop
1284
1285 // remove device Ad already processed
1286 devAds.remove(devFragId);
1287
1288 // find latest and update
1289 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1290 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001291 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001292 localLatest = providerLatest;
1293 }
1294 } // end local provider loop
1295
1296 // checking if remote timestamp is more recent.
1297 Timestamp rOffline = offlineAds.get(deviceId);
1298 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001299 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001300 // remote offline timestamp suggests that the
1301 // device is off-line
1302 markOfflineInternal(deviceId, rOffline);
1303 }
1304
1305 Timestamp lOffline = offline.get(deviceId);
1306 if (lOffline != null && rOffline == null) {
1307 // locally offline, but remote is online, suggest offline
1308 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1309 }
1310
1311 // remove device offline Ad already processed
1312 offlineAds.remove(deviceId);
1313 } // end local device loop
1314 } // device lock
1315
1316 // If there is any Ads left, request them
1317 log.trace("Ads left {}, {}", devAds, portAds);
1318 reqDevices.addAll(devAds.keySet());
1319 reqPorts.addAll(portAds.keySet());
1320
1321 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1322 log.trace("Nothing to request to remote peer {}", sender);
1323 return;
1324 }
1325
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001326 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001327
1328 // 2-way Anti-Entropy for now
1329 try {
1330 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1331 } catch (IOException e) {
1332 log.error("Failed to send response advertisement to " + sender, e);
1333 }
1334
1335// Sketch of 3-way Anti-Entropy
1336// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1337// ClusterMessage message = new ClusterMessage(
1338// clusterService.getLocalNode().id(),
1339// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1340// SERIALIZER.encode(request));
1341//
1342// try {
1343// clusterCommunicator.unicast(message, advertisement.sender());
1344// } catch (IOException e) {
1345// log.error("Failed to send advertisement reply to "
1346// + advertisement.sender(), e);
1347// }
Madan Jampani47c93732014-10-06 20:46:08 -07001348 }
1349
Madan Jampani255a58b2014-10-09 12:08:20 -07001350 private void notifyDelegateIfNotNull(DeviceEvent event) {
1351 if (event != null) {
1352 notifyDelegate(event);
1353 }
1354 }
1355
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001356 private final class SendAdvertisementTask implements Runnable {
1357
1358 @Override
1359 public void run() {
1360 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001361 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001362 return;
1363 }
1364
1365 try {
1366 final NodeId self = clusterService.getLocalNode().id();
1367 Set<ControllerNode> nodes = clusterService.getNodes();
1368
1369 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1370 .transform(toNodeId())
1371 .toList();
1372
1373 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001374 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001375 return;
1376 }
1377
1378 NodeId peer;
1379 do {
1380 int idx = RandomUtils.nextInt(0, nodeIds.size());
1381 peer = nodeIds.get(idx);
1382 } while (peer.equals(self));
1383
1384 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1385
1386 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001387 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001388 return;
1389 }
1390
1391 try {
1392 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1393 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001394 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001395 return;
1396 }
1397 } catch (Exception e) {
1398 // catch all Exception to avoid Scheduled task being suppressed.
1399 log.error("Exception thrown while sending advertisement", e);
1400 }
1401 }
1402 }
1403
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001404 private final class InternalDeviceEventListener
1405 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001406 @Override
1407 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001408 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001409 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001410
Madan Jampani47c93732014-10-06 20:46:08 -07001411 ProviderId providerId = event.providerId();
1412 DeviceId deviceId = event.deviceId();
1413 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001414
Madan Jampani2af244a2015-02-22 13:12:01 -08001415 try {
1416 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1417 } catch (Exception e) {
1418 log.warn("Exception thrown handling device update", e);
1419 }
Madan Jampani47c93732014-10-06 20:46:08 -07001420 }
1421 }
1422
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001423 private final class InternalDeviceOfflineEventListener
1424 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001425 @Override
1426 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001427 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001428 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001429
1430 DeviceId deviceId = event.deviceId();
1431 Timestamp timestamp = event.timestamp();
1432
Madan Jampani2af244a2015-02-22 13:12:01 -08001433 try {
1434 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1435 } catch (Exception e) {
1436 log.warn("Exception thrown handling device offline", e);
1437 }
Madan Jampani25322532014-10-08 11:20:38 -07001438 }
1439 }
1440
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001441 private final class InternalRemoveRequestListener
1442 implements ClusterMessageHandler {
1443 @Override
1444 public void handle(ClusterMessage message) {
1445 log.debug("Received device remove request from peer: {}", message.sender());
1446 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001447
Madan Jampani2af244a2015-02-22 13:12:01 -08001448 try {
1449 removeDevice(did);
1450 } catch (Exception e) {
1451 log.warn("Exception thrown handling device remove", e);
1452 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001453 }
1454 }
1455
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001456 private final class InternalDeviceRemovedEventListener
1457 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001458 @Override
1459 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001460 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001461 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001462
1463 DeviceId deviceId = event.deviceId();
1464 Timestamp timestamp = event.timestamp();
1465
Madan Jampani2af244a2015-02-22 13:12:01 -08001466 try {
1467 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1468 } catch (Exception e) {
1469 log.warn("Exception thrown handling device removed", e);
1470 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001471 }
1472 }
1473
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001474 private final class InternalPortEventListener
1475 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001476 @Override
1477 public void handle(ClusterMessage message) {
1478
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001479 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001480 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001481
1482 ProviderId providerId = event.providerId();
1483 DeviceId deviceId = event.deviceId();
1484 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1485
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001486 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001487 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001488 // Note: dropped information will be recovered by anti-entropy
1489 return;
1490 }
1491
Madan Jampani2af244a2015-02-22 13:12:01 -08001492 try {
1493 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1494 } catch (Exception e) {
1495 log.warn("Exception thrown handling port update", e);
1496 }
Madan Jampani47c93732014-10-06 20:46:08 -07001497 }
1498 }
1499
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001500 private final class InternalPortStatusEventListener
1501 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001502 @Override
1503 public void handle(ClusterMessage message) {
1504
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001505 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001506 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001507
1508 ProviderId providerId = event.providerId();
1509 DeviceId deviceId = event.deviceId();
1510 Timestamped<PortDescription> portDescription = event.portDescription();
1511
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001512 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001513 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001514 // Note: dropped information will be recovered by anti-entropy
1515 return;
1516 }
1517
Madan Jampani2af244a2015-02-22 13:12:01 -08001518 try {
1519 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1520 } catch (Exception e) {
1521 log.warn("Exception thrown handling port update", e);
1522 }
Madan Jampani47c93732014-10-06 20:46:08 -07001523 }
1524 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001525
1526 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001527 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001528 @Override
1529 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001530 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001531 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001532 try {
1533 handleAdvertisement(advertisement);
1534 } catch (Exception e) {
1535 log.warn("Exception thrown handling Device advertisements.", e);
1536 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001537 }
1538 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001539
1540 private final class DeviceInjectedEventListener
1541 implements ClusterMessageHandler {
1542 @Override
1543 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001544 log.debug("Received injected device event from peer: {}", message.sender());
1545 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1546
1547 ProviderId providerId = event.providerId();
1548 DeviceId deviceId = event.deviceId();
1549 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001550 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1551 // workaround for ONOS-1208
1552 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1553 return;
1554 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001555
Madan Jampani2af244a2015-02-22 13:12:01 -08001556 try {
1557 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1558 } catch (Exception e) {
1559 log.warn("Exception thrown handling device injected event.", e);
1560 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001561 }
1562 }
1563
1564 private final class PortInjectedEventListener
1565 implements ClusterMessageHandler {
1566 @Override
1567 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001568 log.debug("Received injected port event from peer: {}", message.sender());
1569 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1570
1571 ProviderId providerId = event.providerId();
1572 DeviceId deviceId = event.deviceId();
1573 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001574 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1575 // workaround for ONOS-1208
1576 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1577 return;
1578 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001579
Madan Jampani2af244a2015-02-22 13:12:01 -08001580 try {
1581 updatePorts(providerId, deviceId, portDescriptions);
1582 } catch (Exception e) {
1583 log.warn("Exception thrown handling port injected event.", e);
1584 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001585 }
1586 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001587
1588 private class InternalPortStatsListener
1589 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1590 @Override
1591 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1592 if (event.type() == PUT) {
1593 Device device = devices.get(event.key());
1594 if (device != null) {
1595 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1596 }
1597 }
1598 }
1599 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001600}