blob: 131000bd56b22f0d375a1ea38fa8916bd797bad7 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
2 * Copyright 2014 Open Networking Laboratory
3 *
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);
307 ClusterMessage clusterMessage = new ClusterMessage(localNode, DEVICE_INJECTED,
308 SERIALIZER.encode(deviceInjectedEvent));
309
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800310 // TODO check unicast return value
311 clusterCommunicator.unicast(clusterMessage, deviceNode);
312 /* error log:
313 log.warn("Failed to process injected device id: {} desc: {} " +
314 "(cluster messaging failed: {})",
315 deviceId, deviceDescription, e);
316 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700317 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800318
319 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700320 }
321
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700322 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
323 DeviceId deviceId,
324 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700325
326 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800327 Map<ProviderId, DeviceDescriptions> device
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700328 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700329
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800330 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700331 // locking per device
332
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700333 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
334 log.debug("Ignoring outdated event: {}", deltaDesc);
335 return null;
336 }
337
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800338 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700339
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700340 final Device oldDevice = devices.get(deviceId);
341 final Device newDevice;
342
343 if (deltaDesc == descs.getDeviceDesc() ||
344 deltaDesc.isNewer(descs.getDeviceDesc())) {
345 // on new device or valid update
346 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800347 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700348 } else {
349 // outdated event, ignored.
350 return null;
351 }
352 if (oldDevice == null) {
353 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700354 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700355 } else {
356 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700357 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700358 }
359 }
360 }
361
362 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700363 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700364 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700365 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700366
367 // update composed device cache
368 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
369 verify(oldDevice == null,
370 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
371 providerId, oldDevice, newDevice);
372
373 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700374 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700375 }
376
377 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
378 }
379
380 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700381 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700382 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700383 Device oldDevice,
384 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700385 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700386 boolean propertiesChanged =
387 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
388 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion());
389 boolean annotationsChanged =
390 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700391
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700392 // Primary providers can respond to all changes, but ancillary ones
393 // should respond only to annotation changes.
394 if ((providerId.isAncillary() && annotationsChanged) ||
395 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700396 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
397 if (!replaced) {
398 verify(replaced,
399 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
400 providerId, oldDevice, devices.get(newDevice.id())
401 , newDevice);
402 }
403 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700404 markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700405 }
406 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
407 }
408
409 // Otherwise merely attempt to change availability if primary provider
410 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700411 boolean added = markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700412 return !added ? null :
413 new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null);
414 }
415 return null;
416 }
417
418 @Override
419 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700420 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700421 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700422 if (event != null) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700423 log.info("Notifying peers of a device offline topology event for deviceId: {} {}",
424 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800425 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700426 }
427 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700428 }
429
430 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
431
432 Map<ProviderId, DeviceDescriptions> providerDescs
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700433 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700434
435 // locking device
436 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700437
438 // accept off-line if given timestamp is newer than
439 // the latest Timestamp from Primary provider
440 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
441 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
442 if (timestamp.compareTo(lastTimestamp) <= 0) {
443 // outdated event ignore
444 return null;
445 }
446
447 offline.put(deviceId, timestamp);
448
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700449 Device device = devices.get(deviceId);
450 if (device == null) {
451 return null;
452 }
453 boolean removed = availableDevices.remove(deviceId);
454 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700455 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700456 }
457 return null;
458 }
459 }
460
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700461 /**
462 * Marks the device as available if the given timestamp is not outdated,
463 * compared to the time the device has been marked offline.
464 *
465 * @param deviceId identifier of the device
466 * @param timestamp of the event triggering this change.
467 * @return true if availability change request was accepted and changed the state
468 */
469 // Guarded by deviceDescs value (=Device lock)
470 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
471 // accept on-line if given timestamp is newer than
472 // the latest offline request Timestamp
473 Timestamp offlineTimestamp = offline.get(deviceId);
474 if (offlineTimestamp == null ||
475 offlineTimestamp.compareTo(timestamp) < 0) {
476
477 offline.remove(deviceId);
478 return availableDevices.add(deviceId);
479 }
480 return false;
481 }
482
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700483 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700484 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
485 DeviceId deviceId,
486 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700487
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800488 NodeId localNode = clusterService.getLocalNode().id();
489 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
490 // since it will trigger distributed store read.
491 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
492 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
493 // If we don't care much about topology performance, then it might be OK.
494 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700495
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800496 // Process port update only if we're the master of the device,
497 // otherwise signal the actual master.
498 List<DeviceEvent> deviceEvents = null;
499 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700500
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800501 final Timestamp newTimestamp;
502 try {
503 newTimestamp = deviceClockService.getTimestamp(deviceId);
504 } catch (IllegalStateException e) {
505 log.info("Timestamp was not available for device {}", deviceId);
506 log.debug(" discarding {}", portDescriptions);
507 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700508
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800509 // Possible situation:
510 // Device connected and became master for short period of time,
511 // but lost mastership before this instance had the chance to
512 // retrieve term information.
513
514 // Information dropped here is expected to be recoverable by
515 // device probing after mastership change
516
517 return Collections.emptyList();
518 }
519 log.debug("timestamp for {} {}", deviceId, newTimestamp);
520
521 final Timestamped<List<PortDescription>> timestampedInput
522 = new Timestamped<>(portDescriptions, newTimestamp);
523 final Timestamped<List<PortDescription>> merged;
524
525 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
526
527 synchronized (device) {
528 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
529 final DeviceDescriptions descs = device.get(providerId);
530 List<PortDescription> mergedList =
531 FluentIterable.from(portDescriptions)
532 .transform(new Function<PortDescription, PortDescription>() {
533 @Override
534 public PortDescription apply(PortDescription input) {
535 // lookup merged port description
536 return descs.getPortDesc(input.portNumber()).value();
537 }
538 }).toList();
539 merged = new Timestamped<List<PortDescription>>(mergedList, newTimestamp);
540 }
541
542 if (!deviceEvents.isEmpty()) {
543 log.info("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
544 providerId, deviceId);
545 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
546 }
547
548 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800549 // FIXME Temporary hack for NPE (ONOS-1171).
550 // Proper fix is to implement forwarding to master on ConfigProvider
551 // redo ONOS-490
552 if (deviceNode == null) {
553 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800554 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800555 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800556
557 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
558 ClusterMessage clusterMessage = new ClusterMessage(
559 localNode, PORT_INJECTED, SERIALIZER.encode(portInjectedEvent));
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800560
561 //TODO check unicast return value
562 clusterCommunicator.unicast(clusterMessage, deviceNode);
563 /* error log:
564 log.warn("Failed to process injected ports of device id: {} " +
565 "(cluster messaging failed: {})",
566 deviceId, e);
567 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700568 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700569
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800570 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700571 }
572
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700573 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
574 DeviceId deviceId,
575 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700576
577 Device device = devices.get(deviceId);
578 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
579
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700580 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700581 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
582
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700583 List<DeviceEvent> events = new ArrayList<>();
584 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700585
586 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
587 log.debug("Ignoring outdated events: {}", portDescriptions);
588 return null;
589 }
590
591 DeviceDescriptions descs = descsMap.get(providerId);
592 // every provider must provide DeviceDescription.
593 checkArgument(descs != null,
594 "Device description for Device ID %s from Provider %s was not found",
595 deviceId, providerId);
596
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700597 Map<PortNumber, Port> ports = getPortMap(deviceId);
598
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700599 final Timestamp newTimestamp = portDescriptions.timestamp();
600
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700601 // Add new ports
602 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700603 for (PortDescription portDescription : portDescriptions.value()) {
604 final PortNumber number = portDescription.portNumber();
605 processed.add(number);
606
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700607 final Port oldPort = ports.get(number);
608 final Port newPort;
609
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700610
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700611 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
612 if (existingPortDesc == null ||
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700613 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700614 // on new port or valid update
615 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700616 descs.putPortDesc(new Timestamped<>(portDescription,
617 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700618 newPort = composePort(device, number, descsMap);
619 } else {
620 // outdated event, ignored.
621 continue;
622 }
623
624 events.add(oldPort == null ?
625 createPort(device, newPort, ports) :
626 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700627 }
628
629 events.addAll(pruneOldPorts(device, ports, processed));
630 }
631 return FluentIterable.from(events).filter(notNull()).toList();
632 }
633
634 // Creates a new port based on the port description adds it to the map and
635 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700636 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700637 private DeviceEvent createPort(Device device, Port newPort,
638 Map<PortNumber, Port> ports) {
639 ports.put(newPort.number(), newPort);
640 return new DeviceEvent(PORT_ADDED, device, newPort);
641 }
642
643 // Checks if the specified port requires update and if so, it replaces the
644 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700645 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700646 private DeviceEvent updatePort(Device device, Port oldPort,
647 Port newPort,
648 Map<PortNumber, Port> ports) {
649 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700650 oldPort.type() != newPort.type() ||
651 oldPort.portSpeed() != newPort.portSpeed() ||
652 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700653 ports.put(oldPort.number(), newPort);
654 return new DeviceEvent(PORT_UPDATED, device, newPort);
655 }
656 return null;
657 }
658
659 // Prunes the specified list of ports based on which ports are in the
660 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700661 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700662 private List<DeviceEvent> pruneOldPorts(Device device,
663 Map<PortNumber, Port> ports,
664 Set<PortNumber> processed) {
665 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700666 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700667 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700668 Entry<PortNumber, Port> e = iterator.next();
669 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700670 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700671 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700672 iterator.remove();
673 }
674 }
675 return events;
676 }
677
678 // Gets the map of ports for the specified device; if one does not already
679 // exist, it creates and registers a new one.
680 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
681 return createIfAbsentUnchecked(devicePorts, deviceId,
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700682 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
683 }
684
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700685 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700686 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700687 Map<ProviderId, DeviceDescriptions> r;
688 r = deviceDescs.get(deviceId);
689 if (r == null) {
690 r = new HashMap<ProviderId, DeviceDescriptions>();
691 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
692 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
693 if (concurrentlyAdded != null) {
694 r = concurrentlyAdded;
695 }
696 }
697 return r;
698 }
699
700 // Guarded by deviceDescs value (=Device lock)
701 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
702 Map<ProviderId, DeviceDescriptions> device,
703 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
704
705 synchronized (device) {
706 DeviceDescriptions r = device.get(providerId);
707 if (r == null) {
708 r = new DeviceDescriptions(deltaDesc);
709 device.put(providerId, r);
710 }
711 return r;
712 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700713 }
714
715 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700716 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
717 DeviceId deviceId,
718 PortDescription portDescription) {
719
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700720 final Timestamp newTimestamp;
721 try {
722 newTimestamp = deviceClockService.getTimestamp(deviceId);
723 } catch (IllegalStateException e) {
724 log.info("Timestamp was not available for device {}", deviceId);
725 log.debug(" discarding {}", portDescription);
726 // Failed to generate timestamp. Ignoring.
727 // See updatePorts comment
728 return null;
729 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700730 final Timestamped<PortDescription> deltaDesc
731 = new Timestamped<>(portDescription, newTimestamp);
732 final DeviceEvent event;
733 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800734 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
735 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700736 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800737 mergedDesc = device.get(providerId)
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700738 .getPortDesc(portDescription.portNumber());
739 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700740 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700741 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
742 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800743 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700744 }
745 return event;
746 }
747
748 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
749 Timestamped<PortDescription> deltaDesc) {
750
751 Device device = devices.get(deviceId);
752 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
753
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700754 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700755 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
756
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700757 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700758
759 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
760 log.debug("Ignoring outdated event: {}", deltaDesc);
761 return null;
762 }
763
764 DeviceDescriptions descs = descsMap.get(providerId);
765 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700766 verify(descs != null,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700767 "Device description for Device ID %s from Provider %s was not found",
768 deviceId, providerId);
769
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700770 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
771 final PortNumber number = deltaDesc.value().portNumber();
772 final Port oldPort = ports.get(number);
773 final Port newPort;
774
775 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
776 if (existingPortDesc == null ||
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700777 deltaDesc.isNewer(existingPortDesc)) {
778 // on new port or valid update
779 // update description
780 descs.putPortDesc(deltaDesc);
781 newPort = composePort(device, number, descsMap);
782 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700783 // same or outdated event, ignored.
784 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700785 return null;
786 }
787
788 if (oldPort == null) {
789 return createPort(device, newPort, ports);
790 } else {
791 return updatePort(device, oldPort, newPort, ports);
792 }
793 }
794 }
795
796 @Override
797 public List<Port> getPorts(DeviceId deviceId) {
798 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
799 if (ports == null) {
800 return Collections.emptyList();
801 }
802 return ImmutableList.copyOf(ports.values());
803 }
804
805 @Override
sangho538108b2015-04-08 14:29:20 -0700806 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
807 Collection<PortStatistics> portStats) {
808
809 ConcurrentMap<PortNumber, PortStatistics> statsMap = devicePortStats.get(deviceId);
810 if (statsMap == null) {
811 statsMap = Maps.newConcurrentMap();
812 devicePortStats.put(deviceId, statsMap);
813 }
814
815 for (PortStatistics stat: portStats) {
816 PortNumber portNumber = PortNumber.portNumber(stat.port());
817 statsMap.put(portNumber, stat);
818 }
819
820 return new DeviceEvent(PORT_STATS_UPDATED, devices.get(deviceId), null);
821 }
822
823 @Override
824 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
825
826 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
827 if (portStats == null) {
828 return Collections.emptyList();
829 }
830 return ImmutableList.copyOf(portStats.values());
831 }
832
833 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700834 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
835 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
836 return ports == null ? null : ports.get(portNumber);
837 }
838
839 @Override
840 public boolean isAvailable(DeviceId deviceId) {
841 return availableDevices.contains(deviceId);
842 }
843
844 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700845 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800846 final NodeId myId = clusterService.getLocalNode().id();
847 NodeId master = mastershipService.getMasterFor(deviceId);
848
849 // if there exist a master, forward
850 // if there is no master, try to become one and process
851
852 boolean relinquishAtEnd = false;
853 if (master == null) {
854 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
855 if (myRole != MastershipRole.NONE) {
856 relinquishAtEnd = true;
857 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800858 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800859 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800860 MastershipTerm term = termService.getMastershipTerm(deviceId);
861 if (myId.equals(term.master())) {
862 master = myId;
863 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700864 }
865
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800866 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800867 log.debug("{} has control of {}, forwarding remove request",
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800868 master, deviceId);
869
870 ClusterMessage message = new ClusterMessage(
871 myId,
872 DEVICE_REMOVE_REQ,
873 SERIALIZER.encode(deviceId));
874
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800875 // TODO check unicast return value
876 clusterCommunicator.unicast(message, master);
877 /* error log:
878 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
879 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800880
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800881 // event will be triggered after master processes it.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800882 return null;
883 }
884
885 // I have control..
886
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700887 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700888 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700889 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800890 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700891 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800892 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700893 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800894 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800895 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800896 mastershipService.relinquishMastership(deviceId);
897 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700898 return event;
899 }
900
901 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
902 Timestamp timestamp) {
903
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700904 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700905 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700906 // accept removal request if given timestamp is newer than
907 // the latest Timestamp from Primary provider
908 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
909 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
910 if (timestamp.compareTo(lastTimestamp) <= 0) {
911 // outdated event ignore
912 return null;
913 }
914 removalRequest.put(deviceId, timestamp);
915
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700916 Device device = devices.remove(deviceId);
917 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700918 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
919 if (ports != null) {
920 ports.clear();
921 }
922 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700923 descs.clear();
924 return device == null ? null :
925 new DeviceEvent(DEVICE_REMOVED, device, null);
926 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700927 }
928
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700929 /**
930 * Checks if given timestamp is superseded by removal request
931 * with more recent timestamp.
932 *
933 * @param deviceId identifier of a device
934 * @param timestampToCheck timestamp of an event to check
935 * @return true if device is already removed
936 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700937 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
938 Timestamp removalTimestamp = removalRequest.get(deviceId);
939 if (removalTimestamp != null &&
940 removalTimestamp.compareTo(timestampToCheck) >= 0) {
941 // removalRequest is more recent
942 return true;
943 }
944 return false;
945 }
946
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700947 /**
948 * Returns a Device, merging description given from multiple Providers.
949 *
950 * @param deviceId device identifier
951 * @param providerDescs Collection of Descriptions from multiple providers
952 * @return Device instance
953 */
954 private Device composeDevice(DeviceId deviceId,
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700955 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700956
Thomas Vachuska444eda62014-10-28 13:09:42 -0700957 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700958
959 ProviderId primary = pickPrimaryPID(providerDescs);
960
961 DeviceDescriptions desc = providerDescs.get(primary);
962
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700963 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700964 Type type = base.type();
965 String manufacturer = base.manufacturer();
966 String hwVersion = base.hwVersion();
967 String swVersion = base.swVersion();
968 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700969 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700970 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
971 annotations = merge(annotations, base.annotations());
972
973 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
974 if (e.getKey().equals(primary)) {
975 continue;
976 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800977 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700978 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700979 // Currently assuming there will never be a key conflict between
980 // providers
981
982 // annotation merging. not so efficient, should revisit later
983 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
984 }
985
986 return new DefaultDevice(primary, deviceId , type, manufacturer,
alshabib7911a052014-10-16 17:49:37 -0700987 hwVersion, swVersion, serialNumber,
988 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700989 }
990
991 /**
992 * Returns a Port, merging description given from multiple Providers.
993 *
994 * @param device device the port is on
995 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700996 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700997 * @return Port instance
998 */
999 private Port composePort(Device device, PortNumber number,
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001000 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001001
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001002 ProviderId primary = pickPrimaryPID(descsMap);
1003 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001004 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001005 boolean isEnabled = false;
1006 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1007
1008 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1009 if (portDesc != null) {
1010 isEnabled = portDesc.value().isEnabled();
1011 annotations = merge(annotations, portDesc.value().annotations());
1012 }
1013
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001014 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001015 if (e.getKey().equals(primary)) {
1016 continue;
1017 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001018 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001019 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001020 // Currently assuming there will never be a key conflict between
1021 // providers
1022
1023 // annotation merging. not so efficient, should revisit later
1024 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1025 if (otherPortDesc != null) {
1026 annotations = merge(annotations, otherPortDesc.value().annotations());
1027 }
1028 }
1029
Thomas Vachuskad16ce182014-10-29 17:25:29 -07001030 return portDesc == null ?
1031 new DefaultPort(device, number, false, annotations) :
1032 new DefaultPort(device, number, isEnabled, portDesc.value().type(),
1033 portDesc.value().portSpeed(), annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001034 }
1035
1036 /**
1037 * @return primary ProviderID, or randomly chosen one if none exists
1038 */
1039 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001040 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001041 ProviderId fallBackPrimary = null;
1042 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1043 if (!e.getKey().isAncillary()) {
1044 return e.getKey();
1045 } else if (fallBackPrimary == null) {
1046 // pick randomly as a fallback in case there is no primary
1047 fallBackPrimary = e.getKey();
1048 }
1049 }
1050 return fallBackPrimary;
1051 }
1052
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001053 private DeviceDescriptions getPrimaryDescriptions(
1054 Map<ProviderId, DeviceDescriptions> providerDescs) {
1055 ProviderId pid = pickPrimaryPID(providerDescs);
1056 return providerDescs.get(pid);
1057 }
1058
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001059 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
1060 ClusterMessage message = new ClusterMessage(
1061 clusterService.getLocalNode().id(),
1062 subject,
1063 SERIALIZER.encode(event));
1064 clusterCommunicator.unicast(message, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001065 }
1066
Jonathan Hart7d656f42015-01-27 14:07:23 -08001067 private void broadcastMessage(MessageSubject subject, Object event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001068 ClusterMessage message = new ClusterMessage(
1069 clusterService.getLocalNode().id(),
1070 subject,
1071 SERIALIZER.encode(event));
1072 clusterCommunicator.broadcast(message);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001073 }
Madan Jampani47c93732014-10-06 20:46:08 -07001074
Jonathan Hart7d656f42015-01-27 14:07:23 -08001075 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001076 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001077 }
1078
Jonathan Hart7d656f42015-01-27 14:07:23 -08001079 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001080 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001081 }
1082
Jonathan Hart7d656f42015-01-27 14:07:23 -08001083 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001084 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001085 }
1086
Jonathan Hart7d656f42015-01-27 14:07:23 -08001087 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001088 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001089 }
1090
Jonathan Hart7d656f42015-01-27 14:07:23 -08001091 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001092 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1093 }
1094
1095 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1096 try {
1097 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1098 } catch (IOException e) {
1099 log.error("Failed to send" + event + " to " + recipient, e);
1100 }
1101 }
1102
1103 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1104 try {
1105 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1106 } catch (IOException e) {
1107 log.error("Failed to send" + event + " to " + recipient, e);
1108 }
1109 }
1110
1111 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1112 try {
1113 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1114 } catch (IOException e) {
1115 log.error("Failed to send" + event + " to " + recipient, e);
1116 }
1117 }
1118
1119 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1120 try {
1121 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1122 } catch (IOException e) {
1123 log.error("Failed to send" + event + " to " + recipient, e);
1124 }
1125 }
1126
1127 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1128 try {
1129 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1130 } catch (IOException e) {
1131 log.error("Failed to send" + event + " to " + recipient, e);
1132 }
1133 }
1134
1135 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1136 final NodeId self = clusterService.getLocalNode().id();
1137
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001138 final int numDevices = deviceDescs.size();
1139 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1140 final int portsPerDevice = 8; // random factor to minimize reallocation
1141 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1142 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001143
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001144 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001145
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001146 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001147 synchronized (devDescs) {
1148
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001149 // send device offline timestamp
1150 Timestamp lOffline = this.offline.get(deviceId);
1151 if (lOffline != null) {
1152 adOffline.put(deviceId, lOffline);
1153 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001154
1155 for (Entry<ProviderId, DeviceDescriptions>
1156 prov : devDescs.entrySet()) {
1157
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001158 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001159 final ProviderId provId = prov.getKey();
1160 final DeviceDescriptions descs = prov.getValue();
1161
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001162 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001163 descs.getDeviceDesc().timestamp());
1164
1165 for (Entry<PortNumber, Timestamped<PortDescription>>
1166 portDesc : descs.getPortDescs().entrySet()) {
1167
1168 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001169 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001170 portDesc.getValue().timestamp());
1171 }
1172 }
1173 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001174 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001175
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001176 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001177 }
1178
1179 /**
1180 * Responds to anti-entropy advertisement message.
1181 * <P>
1182 * Notify sender about out-dated information using regular replication message.
1183 * Send back advertisement to sender if not in sync.
1184 *
1185 * @param advertisement to respond to
1186 */
1187 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1188
1189 final NodeId sender = advertisement.sender();
1190
1191 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1192 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1193 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1194
1195 // Fragments to request
1196 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1197 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1198
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001199 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001200 final DeviceId deviceId = de.getKey();
1201 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1202
1203 synchronized (lDevice) {
1204 // latestTimestamp across provider
1205 // Note: can be null initially
1206 Timestamp localLatest = offline.get(deviceId);
1207
1208 // handle device Ads
1209 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1210 final ProviderId provId = prov.getKey();
1211 final DeviceDescriptions lDeviceDescs = prov.getValue();
1212
1213 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1214
1215
1216 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1217 Timestamp advDevTimestamp = devAds.get(devFragId);
1218
Jonathan Hart403ea932015-02-20 16:23:00 -08001219 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1220 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001221 // remote does not have it or outdated, suggest
1222 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1223 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1224 // local is outdated, request
1225 reqDevices.add(devFragId);
1226 }
1227
1228 // handle port Ads
1229 for (Entry<PortNumber, Timestamped<PortDescription>>
1230 pe : lDeviceDescs.getPortDescs().entrySet()) {
1231
1232 final PortNumber num = pe.getKey();
1233 final Timestamped<PortDescription> lPort = pe.getValue();
1234
1235 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1236
1237 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001238 if (advPortTimestamp == null || lPort.isNewerThan(
1239 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001240 // remote does not have it or outdated, suggest
1241 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1242 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1243 // local is outdated, request
1244 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1245 reqPorts.add(portFragId);
1246 }
1247
1248 // remove port Ad already processed
1249 portAds.remove(portFragId);
1250 } // end local port loop
1251
1252 // remove device Ad already processed
1253 devAds.remove(devFragId);
1254
1255 // find latest and update
1256 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1257 if (localLatest == null ||
1258 providerLatest.compareTo(localLatest) > 0) {
1259 localLatest = providerLatest;
1260 }
1261 } // end local provider loop
1262
1263 // checking if remote timestamp is more recent.
1264 Timestamp rOffline = offlineAds.get(deviceId);
1265 if (rOffline != null &&
1266 rOffline.compareTo(localLatest) > 0) {
1267 // remote offline timestamp suggests that the
1268 // device is off-line
1269 markOfflineInternal(deviceId, rOffline);
1270 }
1271
1272 Timestamp lOffline = offline.get(deviceId);
1273 if (lOffline != null && rOffline == null) {
1274 // locally offline, but remote is online, suggest offline
1275 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1276 }
1277
1278 // remove device offline Ad already processed
1279 offlineAds.remove(deviceId);
1280 } // end local device loop
1281 } // device lock
1282
1283 // If there is any Ads left, request them
1284 log.trace("Ads left {}, {}", devAds, portAds);
1285 reqDevices.addAll(devAds.keySet());
1286 reqPorts.addAll(portAds.keySet());
1287
1288 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1289 log.trace("Nothing to request to remote peer {}", sender);
1290 return;
1291 }
1292
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001293 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001294
1295 // 2-way Anti-Entropy for now
1296 try {
1297 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1298 } catch (IOException e) {
1299 log.error("Failed to send response advertisement to " + sender, e);
1300 }
1301
1302// Sketch of 3-way Anti-Entropy
1303// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1304// ClusterMessage message = new ClusterMessage(
1305// clusterService.getLocalNode().id(),
1306// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1307// SERIALIZER.encode(request));
1308//
1309// try {
1310// clusterCommunicator.unicast(message, advertisement.sender());
1311// } catch (IOException e) {
1312// log.error("Failed to send advertisement reply to "
1313// + advertisement.sender(), e);
1314// }
Madan Jampani47c93732014-10-06 20:46:08 -07001315 }
1316
Madan Jampani255a58b2014-10-09 12:08:20 -07001317 private void notifyDelegateIfNotNull(DeviceEvent event) {
1318 if (event != null) {
1319 notifyDelegate(event);
1320 }
1321 }
1322
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001323 private final class SendAdvertisementTask implements Runnable {
1324
1325 @Override
1326 public void run() {
1327 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001328 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001329 return;
1330 }
1331
1332 try {
1333 final NodeId self = clusterService.getLocalNode().id();
1334 Set<ControllerNode> nodes = clusterService.getNodes();
1335
1336 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1337 .transform(toNodeId())
1338 .toList();
1339
1340 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001341 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001342 return;
1343 }
1344
1345 NodeId peer;
1346 do {
1347 int idx = RandomUtils.nextInt(0, nodeIds.size());
1348 peer = nodeIds.get(idx);
1349 } while (peer.equals(self));
1350
1351 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1352
1353 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001354 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001355 return;
1356 }
1357
1358 try {
1359 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1360 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001361 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001362 return;
1363 }
1364 } catch (Exception e) {
1365 // catch all Exception to avoid Scheduled task being suppressed.
1366 log.error("Exception thrown while sending advertisement", e);
1367 }
1368 }
1369 }
1370
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001371 private final class InternalDeviceEventListener
1372 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001373 @Override
1374 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001375
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001376 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001377 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001378
Madan Jampani47c93732014-10-06 20:46:08 -07001379 ProviderId providerId = event.providerId();
1380 DeviceId deviceId = event.deviceId();
1381 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001382
Madan Jampani2af244a2015-02-22 13:12:01 -08001383 try {
1384 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1385 } catch (Exception e) {
1386 log.warn("Exception thrown handling device update", e);
1387 }
Madan Jampani47c93732014-10-06 20:46:08 -07001388 }
1389 }
1390
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001391 private final class InternalDeviceOfflineEventListener
1392 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001393 @Override
1394 public void handle(ClusterMessage message) {
1395
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001396 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001397 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001398
1399 DeviceId deviceId = event.deviceId();
1400 Timestamp timestamp = event.timestamp();
1401
Madan Jampani2af244a2015-02-22 13:12:01 -08001402 try {
1403 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1404 } catch (Exception e) {
1405 log.warn("Exception thrown handling device offline", e);
1406 }
Madan Jampani25322532014-10-08 11:20:38 -07001407 }
1408 }
1409
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001410 private final class InternalRemoveRequestListener
1411 implements ClusterMessageHandler {
1412 @Override
1413 public void handle(ClusterMessage message) {
1414 log.debug("Received device remove request from peer: {}", message.sender());
1415 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001416
Madan Jampani2af244a2015-02-22 13:12:01 -08001417 try {
1418 removeDevice(did);
1419 } catch (Exception e) {
1420 log.warn("Exception thrown handling device remove", e);
1421 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001422 }
1423 }
1424
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001425 private final class InternalDeviceRemovedEventListener
1426 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001427 @Override
1428 public void handle(ClusterMessage message) {
1429
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001430 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001431 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001432
1433 DeviceId deviceId = event.deviceId();
1434 Timestamp timestamp = event.timestamp();
1435
Madan Jampani2af244a2015-02-22 13:12:01 -08001436 try {
1437 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1438 } catch (Exception e) {
1439 log.warn("Exception thrown handling device removed", e);
1440 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001441 }
1442 }
1443
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001444 private final class InternalPortEventListener
1445 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001446 @Override
1447 public void handle(ClusterMessage message) {
1448
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001449 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001450 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001451
1452 ProviderId providerId = event.providerId();
1453 DeviceId deviceId = event.deviceId();
1454 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1455
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001456 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001457 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001458 // Note: dropped information will be recovered by anti-entropy
1459 return;
1460 }
1461
Madan Jampani2af244a2015-02-22 13:12:01 -08001462 try {
1463 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1464 } catch (Exception e) {
1465 log.warn("Exception thrown handling port update", e);
1466 }
Madan Jampani47c93732014-10-06 20:46:08 -07001467 }
1468 }
1469
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001470 private final class InternalPortStatusEventListener
1471 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001472 @Override
1473 public void handle(ClusterMessage message) {
1474
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001475 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001476 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001477
1478 ProviderId providerId = event.providerId();
1479 DeviceId deviceId = event.deviceId();
1480 Timestamped<PortDescription> portDescription = event.portDescription();
1481
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001482 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001483 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001484 // Note: dropped information will be recovered by anti-entropy
1485 return;
1486 }
1487
Madan Jampani2af244a2015-02-22 13:12:01 -08001488 try {
1489 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1490 } catch (Exception e) {
1491 log.warn("Exception thrown handling port update", e);
1492 }
Madan Jampani47c93732014-10-06 20:46:08 -07001493 }
1494 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001495
1496 private final class InternalDeviceAdvertisementListener
1497 implements ClusterMessageHandler {
1498
1499 @Override
1500 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001501 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001502 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001503 try {
1504 handleAdvertisement(advertisement);
1505 } catch (Exception e) {
1506 log.warn("Exception thrown handling Device advertisements.", e);
1507 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001508 }
1509 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001510
1511 private final class DeviceInjectedEventListener
1512 implements ClusterMessageHandler {
1513 @Override
1514 public void handle(ClusterMessage message) {
1515
1516 log.debug("Received injected device event from peer: {}", message.sender());
1517 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1518
1519 ProviderId providerId = event.providerId();
1520 DeviceId deviceId = event.deviceId();
1521 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001522 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1523 // workaround for ONOS-1208
1524 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1525 return;
1526 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001527
Madan Jampani2af244a2015-02-22 13:12:01 -08001528 try {
1529 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1530 } catch (Exception e) {
1531 log.warn("Exception thrown handling device injected event.", e);
1532 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001533 }
1534 }
1535
1536 private final class PortInjectedEventListener
1537 implements ClusterMessageHandler {
1538 @Override
1539 public void handle(ClusterMessage message) {
1540
1541 log.debug("Received injected port event from peer: {}", message.sender());
1542 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1543
1544 ProviderId providerId = event.providerId();
1545 DeviceId deviceId = event.deviceId();
1546 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001547 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1548 // workaround for ONOS-1208
1549 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1550 return;
1551 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001552
Madan Jampani2af244a2015-02-22 13:12:01 -08001553 try {
1554 updatePorts(providerId, deviceId, portDescriptions);
1555 } catch (Exception e) {
1556 log.warn("Exception thrown handling port injected event.", e);
1557 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001558 }
1559 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001560}