blob: 873a27374e7878e4df287c616cea88e80435f236 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 Open Networking Laboratory
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.store.device.impl;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070017
Yuta HIGUCHI47c40882014-10-10 18:44:37 -070018import com.google.common.base.Function;
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -080019import com.google.common.base.Predicate;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070020import com.google.common.collect.FluentIterable;
21import com.google.common.collect.ImmutableList;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -070022import com.google.common.collect.Maps;
23import com.google.common.collect.Sets;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070024import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070025import org.apache.felix.scr.annotations.Activate;
26import org.apache.felix.scr.annotations.Component;
27import org.apache.felix.scr.annotations.Deactivate;
28import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
30import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080031import org.onlab.packet.ChassisId;
32import org.onlab.util.KryoNamespace;
33import org.onlab.util.NewConcurrentHashMap;
Brian O'Connorabafb502014-12-02 22:26:20 -080034import org.onosproject.cluster.ClusterService;
35import org.onosproject.cluster.ControllerNode;
36import org.onosproject.cluster.NodeId;
37import org.onosproject.mastership.MastershipService;
38import org.onosproject.mastership.MastershipTerm;
39import org.onosproject.mastership.MastershipTermService;
40import 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;
48import org.onosproject.net.Port;
49import org.onosproject.net.PortNumber;
50import org.onosproject.net.device.DeviceClockService;
51import org.onosproject.net.device.DeviceDescription;
52import org.onosproject.net.device.DeviceEvent;
53import org.onosproject.net.device.DeviceStore;
54import org.onosproject.net.device.DeviceStoreDelegate;
55import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070056import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080057import org.onosproject.net.provider.ProviderId;
58import org.onosproject.store.AbstractStore;
59import org.onosproject.store.Timestamp;
60import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
61import org.onosproject.store.cluster.messaging.ClusterMessage;
62import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
63import org.onosproject.store.cluster.messaging.MessageSubject;
64import org.onosproject.store.impl.Timestamped;
65import org.onosproject.store.serializers.KryoSerializer;
66import org.onosproject.store.serializers.impl.DistributedStoreSerializers;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070067import org.slf4j.Logger;
68
Madan Jampani47c93732014-10-06 20:46:08 -070069import java.io.IOException;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070070import java.util.ArrayList;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070071import java.util.Collection;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070072import java.util.Collections;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070073import java.util.HashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070074import java.util.HashSet;
75import java.util.Iterator;
76import java.util.List;
77import java.util.Map;
78import java.util.Map.Entry;
79import java.util.Objects;
80import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070081import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080082import java.util.concurrent.ExecutorService;
83import java.util.concurrent.Executors;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070084import java.util.concurrent.ScheduledExecutorService;
85import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070086
87import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070088import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070089import static com.google.common.base.Verify.verify;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080090import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
91import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080092import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -080093import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080094import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
95import static org.onosproject.net.DefaultAnnotations.merge;
96import static org.onosproject.net.device.DeviceEvent.Type.*;
97import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
98import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
99import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700100
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700101/**
102 * Manages inventory of infrastructure devices using gossip protocol to distribute
103 * information.
104 */
105@Component(immediate = true)
106@Service
107public class GossipDeviceStore
108 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
109 implements DeviceStore {
110
111 private final Logger log = getLogger(getClass());
112
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700113 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800114 // Timeout in milliseconds to process device or ports on remote master node
115 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700116
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700117 // innerMap is used to lock a Device, thus instance should never be replaced.
118 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700119 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700120 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700121
122 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700123 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
124 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
sangho538108b2015-04-08 14:29:20 -0700125 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, PortStatistics>>
126 devicePortStats = Maps.newConcurrentMap();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700127
128 // to be updated under Device lock
129 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
130 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700131
132 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700133 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700134
135 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700136 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700137
Madan Jampani47c93732014-10-06 20:46:08 -0700138 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
139 protected ClusterCommunicationService clusterCommunicator;
140
Madan Jampani53e44e62014-10-07 12:39:51 -0700141 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
142 protected ClusterService clusterService;
143
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700144 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
145 protected MastershipService mastershipService;
146
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800147 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
148 protected MastershipTermService termService;
149
150
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700151 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700152 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700153 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700154 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800155 .register(DistributedStoreSerializers.STORE_COMMON)
156 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
157 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
158 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700159 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800160 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
161 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700162 .register(DeviceAntiEntropyAdvertisement.class)
163 .register(DeviceFragmentId.class)
164 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800165 .register(DeviceInjectedEvent.class)
166 .register(PortInjectedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800167 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700168 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700169 };
170
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800171 private ExecutorService executor;
172
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800173 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700174
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800175 // TODO make these anti-entropy parameters configurable
176 private long initialDelaySec = 5;
177 private long periodSec = 5;
178
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800179
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700180 @Activate
181 public void activate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700182
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800183 executor = Executors.newCachedThreadPool(groupedThreads("onos/device", "fg-%d"));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800184
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800185 backgroundExecutor =
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800186 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700187
Madan Jampani2af244a2015-02-22 13:12:01 -0800188 clusterCommunicator.addSubscriber(
189 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
190 clusterCommunicator.addSubscriber(
191 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
192 new InternalDeviceOfflineEventListener(),
193 executor);
194 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
195 new InternalRemoveRequestListener(),
196 executor);
197 clusterCommunicator.addSubscriber(
198 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
199 clusterCommunicator.addSubscriber(
200 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
201 clusterCommunicator.addSubscriber(
202 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
203 clusterCommunicator.addSubscriber(
204 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
205 new InternalDeviceAdvertisementListener(),
206 backgroundExecutor);
207 clusterCommunicator.addSubscriber(
208 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
209 clusterCommunicator.addSubscriber(
210 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
211
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700212 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800213 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700214 initialDelaySec, periodSec, TimeUnit.SECONDS);
215
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700216 log.info("Started");
217 }
218
219 @Deactivate
220 public void deactivate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700221
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800222 executor.shutdownNow();
223
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800224 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700225 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800226 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700227 log.error("Timeout during executor shutdown");
228 }
229 } catch (InterruptedException e) {
230 log.error("Error during executor shutdown", e);
231 }
232
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700233 deviceDescs.clear();
234 devices.clear();
235 devicePorts.clear();
236 availableDevices.clear();
237 log.info("Stopped");
238 }
239
240 @Override
241 public int getDeviceCount() {
242 return devices.size();
243 }
244
245 @Override
246 public Iterable<Device> getDevices() {
247 return Collections.unmodifiableCollection(devices.values());
248 }
249
250 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800251 public Iterable<Device> getAvailableDevices() {
252 return FluentIterable.from(getDevices())
253 .filter(new Predicate<Device>() {
254
255 @Override
256 public boolean apply(Device input) {
257 return isAvailable(input.id());
258 }
259 });
260 }
261
262 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700263 public Device getDevice(DeviceId deviceId) {
264 return devices.get(deviceId);
265 }
266
267 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700268 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
269 DeviceId deviceId,
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700270 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800271 NodeId localNode = clusterService.getLocalNode().id();
272 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
273
274 // Process device update only if we're the master,
275 // otherwise signal the actual master.
276 DeviceEvent deviceEvent = null;
277 if (localNode.equals(deviceNode)) {
278
279 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
280 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
281 final Timestamped<DeviceDescription> mergedDesc;
282 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
283
284 synchronized (device) {
285 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
286 mergedDesc = device.get(providerId).getDeviceDesc();
287 }
288
289 if (deviceEvent != null) {
290 log.info("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
291 providerId, deviceId);
292 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
293 }
294
295 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800296 // FIXME Temporary hack for NPE (ONOS-1171).
297 // Proper fix is to implement forwarding to master on ConfigProvider
298 // redo ONOS-490
299 if (deviceNode == null) {
300 // silently ignore
301 return null;
302 }
303
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800304
305 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
306 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800307
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800308 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700309 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800310 /* error log:
311 log.warn("Failed to process injected device id: {} desc: {} " +
312 "(cluster messaging failed: {})",
313 deviceId, deviceDescription, e);
314 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700315 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800316
317 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700318 }
319
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700320 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
321 DeviceId deviceId,
322 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700323
324 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800325 Map<ProviderId, DeviceDescriptions> device
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700326 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700327
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800328 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700329 // locking per device
330
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700331 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
332 log.debug("Ignoring outdated event: {}", deltaDesc);
333 return null;
334 }
335
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800336 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700337
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700338 final Device oldDevice = devices.get(deviceId);
339 final Device newDevice;
340
341 if (deltaDesc == descs.getDeviceDesc() ||
342 deltaDesc.isNewer(descs.getDeviceDesc())) {
343 // on new device or valid update
344 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800345 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700346 } else {
347 // outdated event, ignored.
348 return null;
349 }
350 if (oldDevice == null) {
351 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700352 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700353 } else {
354 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700355 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700356 }
357 }
358 }
359
360 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700361 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700362 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700363 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700364
365 // update composed device cache
366 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
367 verify(oldDevice == null,
368 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
369 providerId, oldDevice, newDevice);
370
371 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700372 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700373 }
374
375 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
376 }
377
378 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700379 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700380 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700381 Device oldDevice,
382 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700383 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700384 boolean propertiesChanged =
385 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700386 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
387 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700388 boolean annotationsChanged =
389 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700390
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700391 // Primary providers can respond to all changes, but ancillary ones
392 // should respond only to annotation changes.
393 if ((providerId.isAncillary() && annotationsChanged) ||
394 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700395 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
396 if (!replaced) {
397 verify(replaced,
398 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
399 providerId, oldDevice, devices.get(newDevice.id())
400 , newDevice);
401 }
402 if (!providerId.isAncillary()) {
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700403 boolean wasOnline = availableDevices.contains(newDevice.id());
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700404 markOnline(newDevice.id(), newTimestamp);
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700405 if (!wasOnline) {
406 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
407 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700408 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700409
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700410 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700411 }
412 return null;
413 }
414
415 @Override
416 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700417 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700418 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700419 if (event != null) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700420 log.info("Notifying peers of a device offline topology event for deviceId: {} {}",
421 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800422 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700423 }
424 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700425 }
426
427 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
428
429 Map<ProviderId, DeviceDescriptions> providerDescs
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700430 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700431
432 // locking device
433 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700434
435 // accept off-line if given timestamp is newer than
436 // the latest Timestamp from Primary provider
437 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
438 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
439 if (timestamp.compareTo(lastTimestamp) <= 0) {
440 // outdated event ignore
441 return null;
442 }
443
444 offline.put(deviceId, timestamp);
445
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700446 Device device = devices.get(deviceId);
447 if (device == null) {
448 return null;
449 }
450 boolean removed = availableDevices.remove(deviceId);
451 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700452 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700453 }
454 return null;
455 }
456 }
457
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700458 /**
459 * Marks the device as available if the given timestamp is not outdated,
460 * compared to the time the device has been marked offline.
461 *
462 * @param deviceId identifier of the device
463 * @param timestamp of the event triggering this change.
464 * @return true if availability change request was accepted and changed the state
465 */
466 // Guarded by deviceDescs value (=Device lock)
467 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
468 // accept on-line if given timestamp is newer than
469 // the latest offline request Timestamp
470 Timestamp offlineTimestamp = offline.get(deviceId);
471 if (offlineTimestamp == null ||
472 offlineTimestamp.compareTo(timestamp) < 0) {
473
474 offline.remove(deviceId);
475 return availableDevices.add(deviceId);
476 }
477 return false;
478 }
479
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700480 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700481 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
482 DeviceId deviceId,
483 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700484
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800485 NodeId localNode = clusterService.getLocalNode().id();
486 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
487 // since it will trigger distributed store read.
488 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
489 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
490 // If we don't care much about topology performance, then it might be OK.
491 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700492
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800493 // Process port update only if we're the master of the device,
494 // otherwise signal the actual master.
495 List<DeviceEvent> deviceEvents = null;
496 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700497
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800498 final Timestamp newTimestamp;
499 try {
500 newTimestamp = deviceClockService.getTimestamp(deviceId);
501 } catch (IllegalStateException e) {
502 log.info("Timestamp was not available for device {}", deviceId);
503 log.debug(" discarding {}", portDescriptions);
504 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700505
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800506 // Possible situation:
507 // Device connected and became master for short period of time,
508 // but lost mastership before this instance had the chance to
509 // retrieve term information.
510
511 // Information dropped here is expected to be recoverable by
512 // device probing after mastership change
513
514 return Collections.emptyList();
515 }
516 log.debug("timestamp for {} {}", deviceId, newTimestamp);
517
518 final Timestamped<List<PortDescription>> timestampedInput
519 = new Timestamped<>(portDescriptions, newTimestamp);
520 final Timestamped<List<PortDescription>> merged;
521
522 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
523
524 synchronized (device) {
525 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
526 final DeviceDescriptions descs = device.get(providerId);
527 List<PortDescription> mergedList =
528 FluentIterable.from(portDescriptions)
529 .transform(new Function<PortDescription, PortDescription>() {
530 @Override
531 public PortDescription apply(PortDescription input) {
532 // lookup merged port description
533 return descs.getPortDesc(input.portNumber()).value();
534 }
535 }).toList();
536 merged = new Timestamped<List<PortDescription>>(mergedList, newTimestamp);
537 }
538
539 if (!deviceEvents.isEmpty()) {
540 log.info("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
541 providerId, deviceId);
542 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
543 }
544
545 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800546 // FIXME Temporary hack for NPE (ONOS-1171).
547 // Proper fix is to implement forwarding to master on ConfigProvider
548 // redo ONOS-490
549 if (deviceNode == null) {
550 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800551 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800552 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800553
554 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800555
556 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700557 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800558 /* error log:
559 log.warn("Failed to process injected ports of device id: {} " +
560 "(cluster messaging failed: {})",
561 deviceId, e);
562 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700563 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700564
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800565 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700566 }
567
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700568 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
569 DeviceId deviceId,
570 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700571
572 Device device = devices.get(deviceId);
573 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
574
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700575 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700576 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
577
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700578 List<DeviceEvent> events = new ArrayList<>();
579 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700580
581 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
582 log.debug("Ignoring outdated events: {}", portDescriptions);
583 return null;
584 }
585
586 DeviceDescriptions descs = descsMap.get(providerId);
587 // every provider must provide DeviceDescription.
588 checkArgument(descs != null,
589 "Device description for Device ID %s from Provider %s was not found",
590 deviceId, providerId);
591
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700592 Map<PortNumber, Port> ports = getPortMap(deviceId);
593
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700594 final Timestamp newTimestamp = portDescriptions.timestamp();
595
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700596 // Add new ports
597 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700598 for (PortDescription portDescription : portDescriptions.value()) {
599 final PortNumber number = portDescription.portNumber();
600 processed.add(number);
601
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700602 final Port oldPort = ports.get(number);
603 final Port newPort;
604
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700605
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700606 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
607 if (existingPortDesc == null ||
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700608 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700609 // on new port or valid update
610 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700611 descs.putPortDesc(new Timestamped<>(portDescription,
612 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700613 newPort = composePort(device, number, descsMap);
614 } else {
615 // outdated event, ignored.
616 continue;
617 }
618
619 events.add(oldPort == null ?
620 createPort(device, newPort, ports) :
621 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700622 }
623
624 events.addAll(pruneOldPorts(device, ports, processed));
625 }
626 return FluentIterable.from(events).filter(notNull()).toList();
627 }
628
629 // Creates a new port based on the port description adds it to the map and
630 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700631 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700632 private DeviceEvent createPort(Device device, Port newPort,
633 Map<PortNumber, Port> ports) {
634 ports.put(newPort.number(), newPort);
635 return new DeviceEvent(PORT_ADDED, device, newPort);
636 }
637
638 // Checks if the specified port requires update and if so, it replaces the
639 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700640 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700641 private DeviceEvent updatePort(Device device, Port oldPort,
642 Port newPort,
643 Map<PortNumber, Port> ports) {
644 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700645 oldPort.type() != newPort.type() ||
646 oldPort.portSpeed() != newPort.portSpeed() ||
647 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700648 ports.put(oldPort.number(), newPort);
649 return new DeviceEvent(PORT_UPDATED, device, newPort);
650 }
651 return null;
652 }
653
654 // Prunes the specified list of ports based on which ports are in the
655 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700656 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700657 private List<DeviceEvent> pruneOldPorts(Device device,
658 Map<PortNumber, Port> ports,
659 Set<PortNumber> processed) {
660 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700661 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700662 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700663 Entry<PortNumber, Port> e = iterator.next();
664 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700665 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700666 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700667 iterator.remove();
668 }
669 }
670 return events;
671 }
672
673 // Gets the map of ports for the specified device; if one does not already
674 // exist, it creates and registers a new one.
675 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
676 return createIfAbsentUnchecked(devicePorts, deviceId,
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700677 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
678 }
679
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700680 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700681 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700682 Map<ProviderId, DeviceDescriptions> r;
683 r = deviceDescs.get(deviceId);
684 if (r == null) {
685 r = new HashMap<ProviderId, DeviceDescriptions>();
686 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
687 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
688 if (concurrentlyAdded != null) {
689 r = concurrentlyAdded;
690 }
691 }
692 return r;
693 }
694
695 // Guarded by deviceDescs value (=Device lock)
696 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
697 Map<ProviderId, DeviceDescriptions> device,
698 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
699
700 synchronized (device) {
701 DeviceDescriptions r = device.get(providerId);
702 if (r == null) {
703 r = new DeviceDescriptions(deltaDesc);
704 device.put(providerId, r);
705 }
706 return r;
707 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700708 }
709
710 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700711 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
712 DeviceId deviceId,
713 PortDescription portDescription) {
714
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700715 final Timestamp newTimestamp;
716 try {
717 newTimestamp = deviceClockService.getTimestamp(deviceId);
718 } catch (IllegalStateException e) {
719 log.info("Timestamp was not available for device {}", deviceId);
720 log.debug(" discarding {}", portDescription);
721 // Failed to generate timestamp. Ignoring.
722 // See updatePorts comment
723 return null;
724 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700725 final Timestamped<PortDescription> deltaDesc
726 = new Timestamped<>(portDescription, newTimestamp);
727 final DeviceEvent event;
728 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800729 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
730 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700731 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800732 mergedDesc = device.get(providerId)
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700733 .getPortDesc(portDescription.portNumber());
734 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700735 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700736 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
737 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800738 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700739 }
740 return event;
741 }
742
743 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
744 Timestamped<PortDescription> deltaDesc) {
745
746 Device device = devices.get(deviceId);
747 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
748
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700749 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700750 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
751
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700752 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700753
754 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
755 log.debug("Ignoring outdated event: {}", deltaDesc);
756 return null;
757 }
758
759 DeviceDescriptions descs = descsMap.get(providerId);
760 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700761 verify(descs != null,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700762 "Device description for Device ID %s from Provider %s was not found",
763 deviceId, providerId);
764
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700765 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
766 final PortNumber number = deltaDesc.value().portNumber();
767 final Port oldPort = ports.get(number);
768 final Port newPort;
769
770 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
771 if (existingPortDesc == null ||
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700772 deltaDesc.isNewer(existingPortDesc)) {
773 // on new port or valid update
774 // update description
775 descs.putPortDesc(deltaDesc);
776 newPort = composePort(device, number, descsMap);
777 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700778 // same or outdated event, ignored.
779 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700780 return null;
781 }
782
783 if (oldPort == null) {
784 return createPort(device, newPort, ports);
785 } else {
786 return updatePort(device, oldPort, newPort, ports);
787 }
788 }
789 }
790
791 @Override
792 public List<Port> getPorts(DeviceId deviceId) {
793 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
794 if (ports == null) {
795 return Collections.emptyList();
796 }
797 return ImmutableList.copyOf(ports.values());
798 }
799
800 @Override
sangho538108b2015-04-08 14:29:20 -0700801 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
802 Collection<PortStatistics> portStats) {
803
804 ConcurrentMap<PortNumber, PortStatistics> statsMap = devicePortStats.get(deviceId);
805 if (statsMap == null) {
806 statsMap = Maps.newConcurrentMap();
807 devicePortStats.put(deviceId, statsMap);
808 }
809
810 for (PortStatistics stat: portStats) {
811 PortNumber portNumber = PortNumber.portNumber(stat.port());
812 statsMap.put(portNumber, stat);
813 }
814
815 return new DeviceEvent(PORT_STATS_UPDATED, devices.get(deviceId), null);
816 }
817
818 @Override
819 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
820
821 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
822 if (portStats == null) {
823 return Collections.emptyList();
824 }
825 return ImmutableList.copyOf(portStats.values());
826 }
827
828 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700829 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
830 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
831 return ports == null ? null : ports.get(portNumber);
832 }
833
834 @Override
835 public boolean isAvailable(DeviceId deviceId) {
836 return availableDevices.contains(deviceId);
837 }
838
839 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700840 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800841 final NodeId myId = clusterService.getLocalNode().id();
842 NodeId master = mastershipService.getMasterFor(deviceId);
843
844 // if there exist a master, forward
845 // if there is no master, try to become one and process
846
847 boolean relinquishAtEnd = false;
848 if (master == null) {
849 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
850 if (myRole != MastershipRole.NONE) {
851 relinquishAtEnd = true;
852 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800853 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800854 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800855 MastershipTerm term = termService.getMastershipTerm(deviceId);
856 if (myId.equals(term.master())) {
857 master = myId;
858 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700859 }
860
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800861 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800862 log.debug("{} has control of {}, forwarding remove request",
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800863 master, deviceId);
864
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800865 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700866 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800867 /* error log:
868 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
869 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800870
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800871 // event will be triggered after master processes it.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800872 return null;
873 }
874
875 // I have control..
876
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700877 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700878 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700879 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800880 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700881 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800882 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700883 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800884 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800885 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800886 mastershipService.relinquishMastership(deviceId);
887 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700888 return event;
889 }
890
891 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
892 Timestamp timestamp) {
893
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700894 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700895 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700896 // accept removal request if given timestamp is newer than
897 // the latest Timestamp from Primary provider
898 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
899 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
900 if (timestamp.compareTo(lastTimestamp) <= 0) {
901 // outdated event ignore
902 return null;
903 }
904 removalRequest.put(deviceId, timestamp);
905
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700906 Device device = devices.remove(deviceId);
907 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700908 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
909 if (ports != null) {
910 ports.clear();
911 }
912 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700913 descs.clear();
914 return device == null ? null :
915 new DeviceEvent(DEVICE_REMOVED, device, null);
916 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700917 }
918
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700919 /**
920 * Checks if given timestamp is superseded by removal request
921 * with more recent timestamp.
922 *
923 * @param deviceId identifier of a device
924 * @param timestampToCheck timestamp of an event to check
925 * @return true if device is already removed
926 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700927 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
928 Timestamp removalTimestamp = removalRequest.get(deviceId);
929 if (removalTimestamp != null &&
930 removalTimestamp.compareTo(timestampToCheck) >= 0) {
931 // removalRequest is more recent
932 return true;
933 }
934 return false;
935 }
936
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700937 /**
938 * Returns a Device, merging description given from multiple Providers.
939 *
940 * @param deviceId device identifier
941 * @param providerDescs Collection of Descriptions from multiple providers
942 * @return Device instance
943 */
944 private Device composeDevice(DeviceId deviceId,
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700945 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700946
Thomas Vachuska444eda62014-10-28 13:09:42 -0700947 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700948
949 ProviderId primary = pickPrimaryPID(providerDescs);
950
951 DeviceDescriptions desc = providerDescs.get(primary);
952
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700953 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700954 Type type = base.type();
955 String manufacturer = base.manufacturer();
956 String hwVersion = base.hwVersion();
957 String swVersion = base.swVersion();
958 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700959 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700960 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
961 annotations = merge(annotations, base.annotations());
962
963 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
964 if (e.getKey().equals(primary)) {
965 continue;
966 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800967 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700968 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700969 // Currently assuming there will never be a key conflict between
970 // providers
971
972 // annotation merging. not so efficient, should revisit later
973 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
974 }
975
976 return new DefaultDevice(primary, deviceId , type, manufacturer,
alshabib7911a052014-10-16 17:49:37 -0700977 hwVersion, swVersion, serialNumber,
978 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700979 }
980
981 /**
982 * Returns a Port, merging description given from multiple Providers.
983 *
984 * @param device device the port is on
985 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700986 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700987 * @return Port instance
988 */
989 private Port composePort(Device device, PortNumber number,
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700990 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700991
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700992 ProviderId primary = pickPrimaryPID(descsMap);
993 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700994 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700995 boolean isEnabled = false;
996 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
997
998 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
999 if (portDesc != null) {
1000 isEnabled = portDesc.value().isEnabled();
1001 annotations = merge(annotations, portDesc.value().annotations());
1002 }
1003
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001004 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001005 if (e.getKey().equals(primary)) {
1006 continue;
1007 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001008 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001009 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001010 // Currently assuming there will never be a key conflict between
1011 // providers
1012
1013 // annotation merging. not so efficient, should revisit later
1014 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1015 if (otherPortDesc != null) {
1016 annotations = merge(annotations, otherPortDesc.value().annotations());
1017 }
1018 }
1019
Thomas Vachuskad16ce182014-10-29 17:25:29 -07001020 return portDesc == null ?
1021 new DefaultPort(device, number, false, annotations) :
1022 new DefaultPort(device, number, isEnabled, portDesc.value().type(),
1023 portDesc.value().portSpeed(), annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001024 }
1025
1026 /**
1027 * @return primary ProviderID, or randomly chosen one if none exists
1028 */
1029 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001030 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001031 ProviderId fallBackPrimary = null;
1032 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1033 if (!e.getKey().isAncillary()) {
1034 return e.getKey();
1035 } else if (fallBackPrimary == null) {
1036 // pick randomly as a fallback in case there is no primary
1037 fallBackPrimary = e.getKey();
1038 }
1039 }
1040 return fallBackPrimary;
1041 }
1042
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001043 private DeviceDescriptions getPrimaryDescriptions(
1044 Map<ProviderId, DeviceDescriptions> providerDescs) {
1045 ProviderId pid = pickPrimaryPID(providerDescs);
1046 return providerDescs.get(pid);
1047 }
1048
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001049 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001050 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001051 }
1052
Jonathan Hart7d656f42015-01-27 14:07:23 -08001053 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001054 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001055 }
Madan Jampani47c93732014-10-06 20:46:08 -07001056
Jonathan Hart7d656f42015-01-27 14:07:23 -08001057 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001058 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001059 }
1060
Jonathan Hart7d656f42015-01-27 14:07:23 -08001061 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001062 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001063 }
1064
Jonathan Hart7d656f42015-01-27 14:07:23 -08001065 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001066 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001067 }
1068
Jonathan Hart7d656f42015-01-27 14:07:23 -08001069 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001070 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001071 }
1072
Jonathan Hart7d656f42015-01-27 14:07:23 -08001073 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001074 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1075 }
1076
1077 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1078 try {
1079 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1080 } catch (IOException e) {
1081 log.error("Failed to send" + event + " to " + recipient, e);
1082 }
1083 }
1084
1085 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1086 try {
1087 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1088 } catch (IOException e) {
1089 log.error("Failed to send" + event + " to " + recipient, e);
1090 }
1091 }
1092
1093 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1094 try {
1095 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1096 } catch (IOException e) {
1097 log.error("Failed to send" + event + " to " + recipient, e);
1098 }
1099 }
1100
1101 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1102 try {
1103 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1104 } catch (IOException e) {
1105 log.error("Failed to send" + event + " to " + recipient, e);
1106 }
1107 }
1108
1109 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1110 try {
1111 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1112 } catch (IOException e) {
1113 log.error("Failed to send" + event + " to " + recipient, e);
1114 }
1115 }
1116
1117 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1118 final NodeId self = clusterService.getLocalNode().id();
1119
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001120 final int numDevices = deviceDescs.size();
1121 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1122 final int portsPerDevice = 8; // random factor to minimize reallocation
1123 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1124 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001125
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001126 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001127
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001128 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001129 synchronized (devDescs) {
1130
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001131 // send device offline timestamp
1132 Timestamp lOffline = this.offline.get(deviceId);
1133 if (lOffline != null) {
1134 adOffline.put(deviceId, lOffline);
1135 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001136
1137 for (Entry<ProviderId, DeviceDescriptions>
1138 prov : devDescs.entrySet()) {
1139
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001140 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001141 final ProviderId provId = prov.getKey();
1142 final DeviceDescriptions descs = prov.getValue();
1143
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001144 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001145 descs.getDeviceDesc().timestamp());
1146
1147 for (Entry<PortNumber, Timestamped<PortDescription>>
1148 portDesc : descs.getPortDescs().entrySet()) {
1149
1150 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001151 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001152 portDesc.getValue().timestamp());
1153 }
1154 }
1155 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001156 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001157
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001158 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001159 }
1160
1161 /**
1162 * Responds to anti-entropy advertisement message.
1163 * <P>
1164 * Notify sender about out-dated information using regular replication message.
1165 * Send back advertisement to sender if not in sync.
1166 *
1167 * @param advertisement to respond to
1168 */
1169 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1170
1171 final NodeId sender = advertisement.sender();
1172
1173 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1174 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1175 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1176
1177 // Fragments to request
1178 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1179 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1180
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001181 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001182 final DeviceId deviceId = de.getKey();
1183 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1184
1185 synchronized (lDevice) {
1186 // latestTimestamp across provider
1187 // Note: can be null initially
1188 Timestamp localLatest = offline.get(deviceId);
1189
1190 // handle device Ads
1191 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1192 final ProviderId provId = prov.getKey();
1193 final DeviceDescriptions lDeviceDescs = prov.getValue();
1194
1195 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1196
1197
1198 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1199 Timestamp advDevTimestamp = devAds.get(devFragId);
1200
Jonathan Hart403ea932015-02-20 16:23:00 -08001201 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1202 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001203 // remote does not have it or outdated, suggest
1204 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1205 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1206 // local is outdated, request
1207 reqDevices.add(devFragId);
1208 }
1209
1210 // handle port Ads
1211 for (Entry<PortNumber, Timestamped<PortDescription>>
1212 pe : lDeviceDescs.getPortDescs().entrySet()) {
1213
1214 final PortNumber num = pe.getKey();
1215 final Timestamped<PortDescription> lPort = pe.getValue();
1216
1217 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1218
1219 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001220 if (advPortTimestamp == null || lPort.isNewerThan(
1221 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001222 // remote does not have it or outdated, suggest
1223 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1224 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1225 // local is outdated, request
1226 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1227 reqPorts.add(portFragId);
1228 }
1229
1230 // remove port Ad already processed
1231 portAds.remove(portFragId);
1232 } // end local port loop
1233
1234 // remove device Ad already processed
1235 devAds.remove(devFragId);
1236
1237 // find latest and update
1238 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1239 if (localLatest == null ||
1240 providerLatest.compareTo(localLatest) > 0) {
1241 localLatest = providerLatest;
1242 }
1243 } // end local provider loop
1244
1245 // checking if remote timestamp is more recent.
1246 Timestamp rOffline = offlineAds.get(deviceId);
1247 if (rOffline != null &&
1248 rOffline.compareTo(localLatest) > 0) {
1249 // remote offline timestamp suggests that the
1250 // device is off-line
1251 markOfflineInternal(deviceId, rOffline);
1252 }
1253
1254 Timestamp lOffline = offline.get(deviceId);
1255 if (lOffline != null && rOffline == null) {
1256 // locally offline, but remote is online, suggest offline
1257 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1258 }
1259
1260 // remove device offline Ad already processed
1261 offlineAds.remove(deviceId);
1262 } // end local device loop
1263 } // device lock
1264
1265 // If there is any Ads left, request them
1266 log.trace("Ads left {}, {}", devAds, portAds);
1267 reqDevices.addAll(devAds.keySet());
1268 reqPorts.addAll(portAds.keySet());
1269
1270 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1271 log.trace("Nothing to request to remote peer {}", sender);
1272 return;
1273 }
1274
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001275 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001276
1277 // 2-way Anti-Entropy for now
1278 try {
1279 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1280 } catch (IOException e) {
1281 log.error("Failed to send response advertisement to " + sender, e);
1282 }
1283
1284// Sketch of 3-way Anti-Entropy
1285// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1286// ClusterMessage message = new ClusterMessage(
1287// clusterService.getLocalNode().id(),
1288// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1289// SERIALIZER.encode(request));
1290//
1291// try {
1292// clusterCommunicator.unicast(message, advertisement.sender());
1293// } catch (IOException e) {
1294// log.error("Failed to send advertisement reply to "
1295// + advertisement.sender(), e);
1296// }
Madan Jampani47c93732014-10-06 20:46:08 -07001297 }
1298
Madan Jampani255a58b2014-10-09 12:08:20 -07001299 private void notifyDelegateIfNotNull(DeviceEvent event) {
1300 if (event != null) {
1301 notifyDelegate(event);
1302 }
1303 }
1304
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001305 private final class SendAdvertisementTask implements Runnable {
1306
1307 @Override
1308 public void run() {
1309 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001310 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001311 return;
1312 }
1313
1314 try {
1315 final NodeId self = clusterService.getLocalNode().id();
1316 Set<ControllerNode> nodes = clusterService.getNodes();
1317
1318 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1319 .transform(toNodeId())
1320 .toList();
1321
1322 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001323 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001324 return;
1325 }
1326
1327 NodeId peer;
1328 do {
1329 int idx = RandomUtils.nextInt(0, nodeIds.size());
1330 peer = nodeIds.get(idx);
1331 } while (peer.equals(self));
1332
1333 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1334
1335 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001336 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001337 return;
1338 }
1339
1340 try {
1341 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1342 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001343 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001344 return;
1345 }
1346 } catch (Exception e) {
1347 // catch all Exception to avoid Scheduled task being suppressed.
1348 log.error("Exception thrown while sending advertisement", e);
1349 }
1350 }
1351 }
1352
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001353 private final class InternalDeviceEventListener
1354 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001355 @Override
1356 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001357
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001358 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001359 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001360
Madan Jampani47c93732014-10-06 20:46:08 -07001361 ProviderId providerId = event.providerId();
1362 DeviceId deviceId = event.deviceId();
1363 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001364
Madan Jampani2af244a2015-02-22 13:12:01 -08001365 try {
1366 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1367 } catch (Exception e) {
1368 log.warn("Exception thrown handling device update", e);
1369 }
Madan Jampani47c93732014-10-06 20:46:08 -07001370 }
1371 }
1372
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001373 private final class InternalDeviceOfflineEventListener
1374 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001375 @Override
1376 public void handle(ClusterMessage message) {
1377
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001378 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001379 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001380
1381 DeviceId deviceId = event.deviceId();
1382 Timestamp timestamp = event.timestamp();
1383
Madan Jampani2af244a2015-02-22 13:12:01 -08001384 try {
1385 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1386 } catch (Exception e) {
1387 log.warn("Exception thrown handling device offline", e);
1388 }
Madan Jampani25322532014-10-08 11:20:38 -07001389 }
1390 }
1391
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001392 private final class InternalRemoveRequestListener
1393 implements ClusterMessageHandler {
1394 @Override
1395 public void handle(ClusterMessage message) {
1396 log.debug("Received device remove request from peer: {}", message.sender());
1397 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001398
Madan Jampani2af244a2015-02-22 13:12:01 -08001399 try {
1400 removeDevice(did);
1401 } catch (Exception e) {
1402 log.warn("Exception thrown handling device remove", e);
1403 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001404 }
1405 }
1406
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001407 private final class InternalDeviceRemovedEventListener
1408 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001409 @Override
1410 public void handle(ClusterMessage message) {
1411
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001412 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001413 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001414
1415 DeviceId deviceId = event.deviceId();
1416 Timestamp timestamp = event.timestamp();
1417
Madan Jampani2af244a2015-02-22 13:12:01 -08001418 try {
1419 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1420 } catch (Exception e) {
1421 log.warn("Exception thrown handling device removed", e);
1422 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001423 }
1424 }
1425
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001426 private final class InternalPortEventListener
1427 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001428 @Override
1429 public void handle(ClusterMessage message) {
1430
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001431 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001432 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001433
1434 ProviderId providerId = event.providerId();
1435 DeviceId deviceId = event.deviceId();
1436 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1437
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001438 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001439 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001440 // Note: dropped information will be recovered by anti-entropy
1441 return;
1442 }
1443
Madan Jampani2af244a2015-02-22 13:12:01 -08001444 try {
1445 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1446 } catch (Exception e) {
1447 log.warn("Exception thrown handling port update", e);
1448 }
Madan Jampani47c93732014-10-06 20:46:08 -07001449 }
1450 }
1451
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001452 private final class InternalPortStatusEventListener
1453 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001454 @Override
1455 public void handle(ClusterMessage message) {
1456
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001457 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001458 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001459
1460 ProviderId providerId = event.providerId();
1461 DeviceId deviceId = event.deviceId();
1462 Timestamped<PortDescription> portDescription = event.portDescription();
1463
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001464 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001465 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001466 // Note: dropped information will be recovered by anti-entropy
1467 return;
1468 }
1469
Madan Jampani2af244a2015-02-22 13:12:01 -08001470 try {
1471 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1472 } catch (Exception e) {
1473 log.warn("Exception thrown handling port update", e);
1474 }
Madan Jampani47c93732014-10-06 20:46:08 -07001475 }
1476 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001477
1478 private final class InternalDeviceAdvertisementListener
1479 implements ClusterMessageHandler {
1480
1481 @Override
1482 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001483 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001484 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001485 try {
1486 handleAdvertisement(advertisement);
1487 } catch (Exception e) {
1488 log.warn("Exception thrown handling Device advertisements.", e);
1489 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001490 }
1491 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001492
1493 private final class DeviceInjectedEventListener
1494 implements ClusterMessageHandler {
1495 @Override
1496 public void handle(ClusterMessage message) {
1497
1498 log.debug("Received injected device event from peer: {}", message.sender());
1499 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1500
1501 ProviderId providerId = event.providerId();
1502 DeviceId deviceId = event.deviceId();
1503 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001504 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1505 // workaround for ONOS-1208
1506 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1507 return;
1508 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001509
Madan Jampani2af244a2015-02-22 13:12:01 -08001510 try {
1511 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1512 } catch (Exception e) {
1513 log.warn("Exception thrown handling device injected event.", e);
1514 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001515 }
1516 }
1517
1518 private final class PortInjectedEventListener
1519 implements ClusterMessageHandler {
1520 @Override
1521 public void handle(ClusterMessage message) {
1522
1523 log.debug("Received injected port event from peer: {}", message.sender());
1524 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1525
1526 ProviderId providerId = event.providerId();
1527 DeviceId deviceId = event.deviceId();
1528 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001529 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1530 // workaround for ONOS-1208
1531 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1532 return;
1533 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001534
Madan Jampani2af244a2015-02-22 13:12:01 -08001535 try {
1536 updatePorts(providerId, deviceId, portDescriptions);
1537 } catch (Exception e) {
1538 log.warn("Exception thrown handling port injected event.", e);
1539 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001540 }
1541 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001542}