blob: f16bd06950a2126f1b31d877f25e43446202041b [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;
56import org.onosproject.net.provider.ProviderId;
57import org.onosproject.store.AbstractStore;
58import org.onosproject.store.Timestamp;
59import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
60import org.onosproject.store.cluster.messaging.ClusterMessage;
61import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
62import org.onosproject.store.cluster.messaging.MessageSubject;
63import org.onosproject.store.impl.Timestamped;
64import org.onosproject.store.serializers.KryoSerializer;
65import org.onosproject.store.serializers.impl.DistributedStoreSerializers;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070066import org.slf4j.Logger;
67
Madan Jampani47c93732014-10-06 20:46:08 -070068import java.io.IOException;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070069import java.util.ArrayList;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070070import java.util.Collection;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070071import java.util.Collections;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070072import java.util.HashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070073import java.util.HashSet;
74import java.util.Iterator;
75import java.util.List;
76import java.util.Map;
77import java.util.Map.Entry;
78import java.util.Objects;
79import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070080import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080081import java.util.concurrent.ExecutorService;
82import java.util.concurrent.Executors;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070083import java.util.concurrent.ScheduledExecutorService;
84import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070085
86import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070087import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070088import static com.google.common.base.Verify.verify;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080089import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
90import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080091import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -080092import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080093import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
94import static org.onosproject.net.DefaultAnnotations.merge;
95import static org.onosproject.net.device.DeviceEvent.Type.*;
96import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
97import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
98import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070099
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700100/**
101 * Manages inventory of infrastructure devices using gossip protocol to distribute
102 * information.
103 */
104@Component(immediate = true)
105@Service
106public class GossipDeviceStore
107 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
108 implements DeviceStore {
109
110 private final Logger log = getLogger(getClass());
111
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700112 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800113 // Timeout in milliseconds to process device or ports on remote master node
114 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700115
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700116 // innerMap is used to lock a Device, thus instance should never be replaced.
117 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700118 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700119 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700120
121 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700122 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
123 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
124
125 // to be updated under Device lock
126 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
127 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700128
129 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700130 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700131
132 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700133 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700134
Madan Jampani47c93732014-10-06 20:46:08 -0700135 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
136 protected ClusterCommunicationService clusterCommunicator;
137
Madan Jampani53e44e62014-10-07 12:39:51 -0700138 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
139 protected ClusterService clusterService;
140
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700141 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
142 protected MastershipService mastershipService;
143
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800144 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
145 protected MastershipTermService termService;
146
147
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700148 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700149 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700150 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700151 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800152 .register(DistributedStoreSerializers.STORE_COMMON)
153 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
154 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
155 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700156 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800157 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
158 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700159 .register(DeviceAntiEntropyAdvertisement.class)
160 .register(DeviceFragmentId.class)
161 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800162 .register(DeviceInjectedEvent.class)
163 .register(PortInjectedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800164 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700165 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700166 };
167
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800168 private ExecutorService executor;
169
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800170 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700171
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800172 // TODO make these anti-entropy parameters configurable
173 private long initialDelaySec = 5;
174 private long periodSec = 5;
175
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800176
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700177 @Activate
178 public void activate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700179
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800180 executor = Executors.newCachedThreadPool(groupedThreads("onos/device", "fg-%d"));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800181
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800182 backgroundExecutor =
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800183 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700184
Madan Jampani2af244a2015-02-22 13:12:01 -0800185 clusterCommunicator.addSubscriber(
186 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
187 clusterCommunicator.addSubscriber(
188 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
189 new InternalDeviceOfflineEventListener(),
190 executor);
191 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
192 new InternalRemoveRequestListener(),
193 executor);
194 clusterCommunicator.addSubscriber(
195 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
196 clusterCommunicator.addSubscriber(
197 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
198 clusterCommunicator.addSubscriber(
199 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
200 clusterCommunicator.addSubscriber(
201 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
202 new InternalDeviceAdvertisementListener(),
203 backgroundExecutor);
204 clusterCommunicator.addSubscriber(
205 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
206 clusterCommunicator.addSubscriber(
207 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
208
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700209 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800210 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700211 initialDelaySec, periodSec, TimeUnit.SECONDS);
212
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700213 log.info("Started");
214 }
215
216 @Deactivate
217 public void deactivate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700218
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800219 executor.shutdownNow();
220
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800221 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700222 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800223 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700224 log.error("Timeout during executor shutdown");
225 }
226 } catch (InterruptedException e) {
227 log.error("Error during executor shutdown", e);
228 }
229
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700230 deviceDescs.clear();
231 devices.clear();
232 devicePorts.clear();
233 availableDevices.clear();
234 log.info("Stopped");
235 }
236
237 @Override
238 public int getDeviceCount() {
239 return devices.size();
240 }
241
242 @Override
243 public Iterable<Device> getDevices() {
244 return Collections.unmodifiableCollection(devices.values());
245 }
246
247 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800248 public Iterable<Device> getAvailableDevices() {
249 return FluentIterable.from(getDevices())
250 .filter(new Predicate<Device>() {
251
252 @Override
253 public boolean apply(Device input) {
254 return isAvailable(input.id());
255 }
256 });
257 }
258
259 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700260 public Device getDevice(DeviceId deviceId) {
261 return devices.get(deviceId);
262 }
263
264 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700265 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
266 DeviceId deviceId,
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700267 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800268 NodeId localNode = clusterService.getLocalNode().id();
269 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
270
271 // Process device update only if we're the master,
272 // otherwise signal the actual master.
273 DeviceEvent deviceEvent = null;
274 if (localNode.equals(deviceNode)) {
275
276 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
277 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
278 final Timestamped<DeviceDescription> mergedDesc;
279 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
280
281 synchronized (device) {
282 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
283 mergedDesc = device.get(providerId).getDeviceDesc();
284 }
285
286 if (deviceEvent != null) {
287 log.info("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
288 providerId, deviceId);
289 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
290 }
291
292 } else {
293
294 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
295 providerId, deviceId, deviceDescription);
296 ClusterMessage clusterMessage = new ClusterMessage(localNode, DEVICE_INJECTED,
297 SERIALIZER.encode(deviceInjectedEvent));
298
299 try {
300 clusterCommunicator.unicast(clusterMessage, deviceNode);
301 } catch (IOException e) {
302 log.warn("Failed to process injected device id: {} desc: {} " +
303 "(cluster messaging failed: {})",
304 deviceId, deviceDescription, e);
305 }
306
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700307 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800308
309 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700310 }
311
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700312 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
313 DeviceId deviceId,
314 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700315
316 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800317 Map<ProviderId, DeviceDescriptions> device
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700318 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700319
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800320 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700321 // locking per device
322
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700323 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
324 log.debug("Ignoring outdated event: {}", deltaDesc);
325 return null;
326 }
327
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800328 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700329
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700330 final Device oldDevice = devices.get(deviceId);
331 final Device newDevice;
332
333 if (deltaDesc == descs.getDeviceDesc() ||
334 deltaDesc.isNewer(descs.getDeviceDesc())) {
335 // on new device or valid update
336 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800337 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700338 } else {
339 // outdated event, ignored.
340 return null;
341 }
342 if (oldDevice == null) {
343 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700344 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700345 } else {
346 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700347 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700348 }
349 }
350 }
351
352 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700353 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700354 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700355 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700356
357 // update composed device cache
358 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
359 verify(oldDevice == null,
360 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
361 providerId, oldDevice, newDevice);
362
363 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700364 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700365 }
366
367 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
368 }
369
370 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700371 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700372 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700373 Device oldDevice,
374 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700375 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700376 boolean propertiesChanged =
377 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
378 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion());
379 boolean annotationsChanged =
380 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700381
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700382 // Primary providers can respond to all changes, but ancillary ones
383 // should respond only to annotation changes.
384 if ((providerId.isAncillary() && annotationsChanged) ||
385 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700386 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
387 if (!replaced) {
388 verify(replaced,
389 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
390 providerId, oldDevice, devices.get(newDevice.id())
391 , newDevice);
392 }
393 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700394 markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700395 }
396 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
397 }
398
399 // Otherwise merely attempt to change availability if primary provider
400 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700401 boolean added = markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700402 return !added ? null :
403 new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null);
404 }
405 return null;
406 }
407
408 @Override
409 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700410 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700411 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700412 if (event != null) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700413 log.info("Notifying peers of a device offline topology event for deviceId: {} {}",
414 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800415 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700416 }
417 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700418 }
419
420 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
421
422 Map<ProviderId, DeviceDescriptions> providerDescs
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700423 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700424
425 // locking device
426 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700427
428 // accept off-line if given timestamp is newer than
429 // the latest Timestamp from Primary provider
430 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
431 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
432 if (timestamp.compareTo(lastTimestamp) <= 0) {
433 // outdated event ignore
434 return null;
435 }
436
437 offline.put(deviceId, timestamp);
438
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700439 Device device = devices.get(deviceId);
440 if (device == null) {
441 return null;
442 }
443 boolean removed = availableDevices.remove(deviceId);
444 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700445 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700446 }
447 return null;
448 }
449 }
450
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700451 /**
452 * Marks the device as available if the given timestamp is not outdated,
453 * compared to the time the device has been marked offline.
454 *
455 * @param deviceId identifier of the device
456 * @param timestamp of the event triggering this change.
457 * @return true if availability change request was accepted and changed the state
458 */
459 // Guarded by deviceDescs value (=Device lock)
460 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
461 // accept on-line if given timestamp is newer than
462 // the latest offline request Timestamp
463 Timestamp offlineTimestamp = offline.get(deviceId);
464 if (offlineTimestamp == null ||
465 offlineTimestamp.compareTo(timestamp) < 0) {
466
467 offline.remove(deviceId);
468 return availableDevices.add(deviceId);
469 }
470 return false;
471 }
472
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700473 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700474 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
475 DeviceId deviceId,
476 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700477
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800478 NodeId localNode = clusterService.getLocalNode().id();
479 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
480 // since it will trigger distributed store read.
481 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
482 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
483 // If we don't care much about topology performance, then it might be OK.
484 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700485
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800486 // Process port update only if we're the master of the device,
487 // otherwise signal the actual master.
488 List<DeviceEvent> deviceEvents = null;
489 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700490
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800491 final Timestamp newTimestamp;
492 try {
493 newTimestamp = deviceClockService.getTimestamp(deviceId);
494 } catch (IllegalStateException e) {
495 log.info("Timestamp was not available for device {}", deviceId);
496 log.debug(" discarding {}", portDescriptions);
497 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700498
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800499 // Possible situation:
500 // Device connected and became master for short period of time,
501 // but lost mastership before this instance had the chance to
502 // retrieve term information.
503
504 // Information dropped here is expected to be recoverable by
505 // device probing after mastership change
506
507 return Collections.emptyList();
508 }
509 log.debug("timestamp for {} {}", deviceId, newTimestamp);
510
511 final Timestamped<List<PortDescription>> timestampedInput
512 = new Timestamped<>(portDescriptions, newTimestamp);
513 final Timestamped<List<PortDescription>> merged;
514
515 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
516
517 synchronized (device) {
518 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
519 final DeviceDescriptions descs = device.get(providerId);
520 List<PortDescription> mergedList =
521 FluentIterable.from(portDescriptions)
522 .transform(new Function<PortDescription, PortDescription>() {
523 @Override
524 public PortDescription apply(PortDescription input) {
525 // lookup merged port description
526 return descs.getPortDesc(input.portNumber()).value();
527 }
528 }).toList();
529 merged = new Timestamped<List<PortDescription>>(mergedList, newTimestamp);
530 }
531
532 if (!deviceEvents.isEmpty()) {
533 log.info("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
534 providerId, deviceId);
535 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
536 }
537
538 } else {
539
540 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
541 ClusterMessage clusterMessage = new ClusterMessage(
542 localNode, PORT_INJECTED, SERIALIZER.encode(portInjectedEvent));
543 try {
544 clusterCommunicator.unicast(clusterMessage, deviceNode);
545 } catch (IOException e) {
546 log.warn("Failed to process injected ports of device id: {} " +
547 "(cluster messaging failed: {})",
548 deviceId, e);
549 }
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700550 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700551
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800552 return deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700553 }
554
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700555 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
556 DeviceId deviceId,
557 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700558
559 Device device = devices.get(deviceId);
560 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
561
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700562 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700563 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
564
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700565 List<DeviceEvent> events = new ArrayList<>();
566 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700567
568 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
569 log.debug("Ignoring outdated events: {}", portDescriptions);
570 return null;
571 }
572
573 DeviceDescriptions descs = descsMap.get(providerId);
574 // every provider must provide DeviceDescription.
575 checkArgument(descs != null,
576 "Device description for Device ID %s from Provider %s was not found",
577 deviceId, providerId);
578
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700579 Map<PortNumber, Port> ports = getPortMap(deviceId);
580
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700581 final Timestamp newTimestamp = portDescriptions.timestamp();
582
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700583 // Add new ports
584 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700585 for (PortDescription portDescription : portDescriptions.value()) {
586 final PortNumber number = portDescription.portNumber();
587 processed.add(number);
588
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700589 final Port oldPort = ports.get(number);
590 final Port newPort;
591
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700592
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700593 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
594 if (existingPortDesc == null ||
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700595 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700596 // on new port or valid update
597 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700598 descs.putPortDesc(new Timestamped<>(portDescription,
599 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700600 newPort = composePort(device, number, descsMap);
601 } else {
602 // outdated event, ignored.
603 continue;
604 }
605
606 events.add(oldPort == null ?
607 createPort(device, newPort, ports) :
608 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700609 }
610
611 events.addAll(pruneOldPorts(device, ports, processed));
612 }
613 return FluentIterable.from(events).filter(notNull()).toList();
614 }
615
616 // Creates a new port based on the port description adds it to the map and
617 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700618 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700619 private DeviceEvent createPort(Device device, Port newPort,
620 Map<PortNumber, Port> ports) {
621 ports.put(newPort.number(), newPort);
622 return new DeviceEvent(PORT_ADDED, device, newPort);
623 }
624
625 // Checks if the specified port requires update and if so, it replaces the
626 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700627 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700628 private DeviceEvent updatePort(Device device, Port oldPort,
629 Port newPort,
630 Map<PortNumber, Port> ports) {
631 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700632 oldPort.type() != newPort.type() ||
633 oldPort.portSpeed() != newPort.portSpeed() ||
634 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700635 ports.put(oldPort.number(), newPort);
636 return new DeviceEvent(PORT_UPDATED, device, newPort);
637 }
638 return null;
639 }
640
641 // Prunes the specified list of ports based on which ports are in the
642 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700643 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700644 private List<DeviceEvent> pruneOldPorts(Device device,
645 Map<PortNumber, Port> ports,
646 Set<PortNumber> processed) {
647 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700648 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700649 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700650 Entry<PortNumber, Port> e = iterator.next();
651 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700652 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700653 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700654 iterator.remove();
655 }
656 }
657 return events;
658 }
659
660 // Gets the map of ports for the specified device; if one does not already
661 // exist, it creates and registers a new one.
662 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
663 return createIfAbsentUnchecked(devicePorts, deviceId,
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700664 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
665 }
666
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700667 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700668 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700669 Map<ProviderId, DeviceDescriptions> r;
670 r = deviceDescs.get(deviceId);
671 if (r == null) {
672 r = new HashMap<ProviderId, DeviceDescriptions>();
673 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
674 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
675 if (concurrentlyAdded != null) {
676 r = concurrentlyAdded;
677 }
678 }
679 return r;
680 }
681
682 // Guarded by deviceDescs value (=Device lock)
683 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
684 Map<ProviderId, DeviceDescriptions> device,
685 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
686
687 synchronized (device) {
688 DeviceDescriptions r = device.get(providerId);
689 if (r == null) {
690 r = new DeviceDescriptions(deltaDesc);
691 device.put(providerId, r);
692 }
693 return r;
694 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700695 }
696
697 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700698 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
699 DeviceId deviceId,
700 PortDescription portDescription) {
701
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700702 final Timestamp newTimestamp;
703 try {
704 newTimestamp = deviceClockService.getTimestamp(deviceId);
705 } catch (IllegalStateException e) {
706 log.info("Timestamp was not available for device {}", deviceId);
707 log.debug(" discarding {}", portDescription);
708 // Failed to generate timestamp. Ignoring.
709 // See updatePorts comment
710 return null;
711 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700712 final Timestamped<PortDescription> deltaDesc
713 = new Timestamped<>(portDescription, newTimestamp);
714 final DeviceEvent event;
715 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800716 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
717 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700718 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800719 mergedDesc = device.get(providerId)
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700720 .getPortDesc(portDescription.portNumber());
721 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700722 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700723 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
724 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800725 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700726 }
727 return event;
728 }
729
730 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
731 Timestamped<PortDescription> deltaDesc) {
732
733 Device device = devices.get(deviceId);
734 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
735
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700736 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700737 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
738
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700739 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700740
741 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
742 log.debug("Ignoring outdated event: {}", deltaDesc);
743 return null;
744 }
745
746 DeviceDescriptions descs = descsMap.get(providerId);
747 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700748 verify(descs != null,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700749 "Device description for Device ID %s from Provider %s was not found",
750 deviceId, providerId);
751
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700752 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
753 final PortNumber number = deltaDesc.value().portNumber();
754 final Port oldPort = ports.get(number);
755 final Port newPort;
756
757 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
758 if (existingPortDesc == null ||
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700759 deltaDesc.isNewer(existingPortDesc)) {
760 // on new port or valid update
761 // update description
762 descs.putPortDesc(deltaDesc);
763 newPort = composePort(device, number, descsMap);
764 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700765 // same or outdated event, ignored.
766 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700767 return null;
768 }
769
770 if (oldPort == null) {
771 return createPort(device, newPort, ports);
772 } else {
773 return updatePort(device, oldPort, newPort, ports);
774 }
775 }
776 }
777
778 @Override
779 public List<Port> getPorts(DeviceId deviceId) {
780 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
781 if (ports == null) {
782 return Collections.emptyList();
783 }
784 return ImmutableList.copyOf(ports.values());
785 }
786
787 @Override
788 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
789 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
790 return ports == null ? null : ports.get(portNumber);
791 }
792
793 @Override
794 public boolean isAvailable(DeviceId deviceId) {
795 return availableDevices.contains(deviceId);
796 }
797
798 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700799 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800800 final NodeId myId = clusterService.getLocalNode().id();
801 NodeId master = mastershipService.getMasterFor(deviceId);
802
803 // if there exist a master, forward
804 // if there is no master, try to become one and process
805
806 boolean relinquishAtEnd = false;
807 if (master == null) {
808 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
809 if (myRole != MastershipRole.NONE) {
810 relinquishAtEnd = true;
811 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800812 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800813 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800814 MastershipTerm term = termService.getMastershipTerm(deviceId);
815 if (myId.equals(term.master())) {
816 master = myId;
817 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700818 }
819
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800820 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800821 log.debug("{} has control of {}, forwarding remove request",
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800822 master, deviceId);
823
824 ClusterMessage message = new ClusterMessage(
825 myId,
826 DEVICE_REMOVE_REQ,
827 SERIALIZER.encode(deviceId));
828
829 try {
830 clusterCommunicator.unicast(message, master);
831 } catch (IOException e) {
832 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
833 }
834
835 // event will be triggered after master processes it.
836 return null;
837 }
838
839 // I have control..
840
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700841 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700842 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700843 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800844 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700845 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800846 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700847 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800848 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800849 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800850 mastershipService.relinquishMastership(deviceId);
851 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700852 return event;
853 }
854
855 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
856 Timestamp timestamp) {
857
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700858 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700859 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700860 // accept removal request if given timestamp is newer than
861 // the latest Timestamp from Primary provider
862 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
863 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
864 if (timestamp.compareTo(lastTimestamp) <= 0) {
865 // outdated event ignore
866 return null;
867 }
868 removalRequest.put(deviceId, timestamp);
869
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700870 Device device = devices.remove(deviceId);
871 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700872 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
873 if (ports != null) {
874 ports.clear();
875 }
876 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700877 descs.clear();
878 return device == null ? null :
879 new DeviceEvent(DEVICE_REMOVED, device, null);
880 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700881 }
882
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700883 /**
884 * Checks if given timestamp is superseded by removal request
885 * with more recent timestamp.
886 *
887 * @param deviceId identifier of a device
888 * @param timestampToCheck timestamp of an event to check
889 * @return true if device is already removed
890 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700891 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
892 Timestamp removalTimestamp = removalRequest.get(deviceId);
893 if (removalTimestamp != null &&
894 removalTimestamp.compareTo(timestampToCheck) >= 0) {
895 // removalRequest is more recent
896 return true;
897 }
898 return false;
899 }
900
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700901 /**
902 * Returns a Device, merging description given from multiple Providers.
903 *
904 * @param deviceId device identifier
905 * @param providerDescs Collection of Descriptions from multiple providers
906 * @return Device instance
907 */
908 private Device composeDevice(DeviceId deviceId,
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700909 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700910
Thomas Vachuska444eda62014-10-28 13:09:42 -0700911 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700912
913 ProviderId primary = pickPrimaryPID(providerDescs);
914
915 DeviceDescriptions desc = providerDescs.get(primary);
916
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700917 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700918 Type type = base.type();
919 String manufacturer = base.manufacturer();
920 String hwVersion = base.hwVersion();
921 String swVersion = base.swVersion();
922 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700923 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700924 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
925 annotations = merge(annotations, base.annotations());
926
927 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
928 if (e.getKey().equals(primary)) {
929 continue;
930 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800931 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700932 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700933 // Currently assuming there will never be a key conflict between
934 // providers
935
936 // annotation merging. not so efficient, should revisit later
937 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
938 }
939
940 return new DefaultDevice(primary, deviceId , type, manufacturer,
alshabib7911a052014-10-16 17:49:37 -0700941 hwVersion, swVersion, serialNumber,
942 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700943 }
944
945 /**
946 * Returns a Port, merging description given from multiple Providers.
947 *
948 * @param device device the port is on
949 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700950 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700951 * @return Port instance
952 */
953 private Port composePort(Device device, PortNumber number,
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700954 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700955
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700956 ProviderId primary = pickPrimaryPID(descsMap);
957 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700958 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700959 boolean isEnabled = false;
960 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
961
962 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
963 if (portDesc != null) {
964 isEnabled = portDesc.value().isEnabled();
965 annotations = merge(annotations, portDesc.value().annotations());
966 }
967
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700968 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700969 if (e.getKey().equals(primary)) {
970 continue;
971 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800972 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700973 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700974 // Currently assuming there will never be a key conflict between
975 // providers
976
977 // annotation merging. not so efficient, should revisit later
978 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
979 if (otherPortDesc != null) {
980 annotations = merge(annotations, otherPortDesc.value().annotations());
981 }
982 }
983
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700984 return portDesc == null ?
985 new DefaultPort(device, number, false, annotations) :
986 new DefaultPort(device, number, isEnabled, portDesc.value().type(),
987 portDesc.value().portSpeed(), annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700988 }
989
990 /**
991 * @return primary ProviderID, or randomly chosen one if none exists
992 */
993 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700994 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700995 ProviderId fallBackPrimary = null;
996 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
997 if (!e.getKey().isAncillary()) {
998 return e.getKey();
999 } else if (fallBackPrimary == null) {
1000 // pick randomly as a fallback in case there is no primary
1001 fallBackPrimary = e.getKey();
1002 }
1003 }
1004 return fallBackPrimary;
1005 }
1006
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001007 private DeviceDescriptions getPrimaryDescriptions(
1008 Map<ProviderId, DeviceDescriptions> providerDescs) {
1009 ProviderId pid = pickPrimaryPID(providerDescs);
1010 return providerDescs.get(pid);
1011 }
1012
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001013 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
1014 ClusterMessage message = new ClusterMessage(
1015 clusterService.getLocalNode().id(),
1016 subject,
1017 SERIALIZER.encode(event));
1018 clusterCommunicator.unicast(message, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001019 }
1020
Jonathan Hart7d656f42015-01-27 14:07:23 -08001021 private void broadcastMessage(MessageSubject subject, Object event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001022 ClusterMessage message = new ClusterMessage(
1023 clusterService.getLocalNode().id(),
1024 subject,
1025 SERIALIZER.encode(event));
1026 clusterCommunicator.broadcast(message);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001027 }
Madan Jampani47c93732014-10-06 20:46:08 -07001028
Jonathan Hart7d656f42015-01-27 14:07:23 -08001029 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001030 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001031 }
1032
Jonathan Hart7d656f42015-01-27 14:07:23 -08001033 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001034 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001035 }
1036
Jonathan Hart7d656f42015-01-27 14:07:23 -08001037 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001038 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001039 }
1040
Jonathan Hart7d656f42015-01-27 14:07:23 -08001041 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001042 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001043 }
1044
Jonathan Hart7d656f42015-01-27 14:07:23 -08001045 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001046 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1047 }
1048
1049 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1050 try {
1051 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1052 } catch (IOException e) {
1053 log.error("Failed to send" + event + " to " + recipient, e);
1054 }
1055 }
1056
1057 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1058 try {
1059 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1060 } catch (IOException e) {
1061 log.error("Failed to send" + event + " to " + recipient, e);
1062 }
1063 }
1064
1065 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1066 try {
1067 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1068 } catch (IOException e) {
1069 log.error("Failed to send" + event + " to " + recipient, e);
1070 }
1071 }
1072
1073 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1074 try {
1075 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1076 } catch (IOException e) {
1077 log.error("Failed to send" + event + " to " + recipient, e);
1078 }
1079 }
1080
1081 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1082 try {
1083 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1084 } catch (IOException e) {
1085 log.error("Failed to send" + event + " to " + recipient, e);
1086 }
1087 }
1088
1089 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1090 final NodeId self = clusterService.getLocalNode().id();
1091
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001092 final int numDevices = deviceDescs.size();
1093 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1094 final int portsPerDevice = 8; // random factor to minimize reallocation
1095 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1096 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001097
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001098 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001099
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001100 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001101 synchronized (devDescs) {
1102
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001103 // send device offline timestamp
1104 Timestamp lOffline = this.offline.get(deviceId);
1105 if (lOffline != null) {
1106 adOffline.put(deviceId, lOffline);
1107 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001108
1109 for (Entry<ProviderId, DeviceDescriptions>
1110 prov : devDescs.entrySet()) {
1111
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001112 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001113 final ProviderId provId = prov.getKey();
1114 final DeviceDescriptions descs = prov.getValue();
1115
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001116 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001117 descs.getDeviceDesc().timestamp());
1118
1119 for (Entry<PortNumber, Timestamped<PortDescription>>
1120 portDesc : descs.getPortDescs().entrySet()) {
1121
1122 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001123 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001124 portDesc.getValue().timestamp());
1125 }
1126 }
1127 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001128 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001129
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001130 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001131 }
1132
1133 /**
1134 * Responds to anti-entropy advertisement message.
1135 * <P>
1136 * Notify sender about out-dated information using regular replication message.
1137 * Send back advertisement to sender if not in sync.
1138 *
1139 * @param advertisement to respond to
1140 */
1141 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1142
1143 final NodeId sender = advertisement.sender();
1144
1145 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1146 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1147 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1148
1149 // Fragments to request
1150 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1151 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1152
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001153 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001154 final DeviceId deviceId = de.getKey();
1155 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1156
1157 synchronized (lDevice) {
1158 // latestTimestamp across provider
1159 // Note: can be null initially
1160 Timestamp localLatest = offline.get(deviceId);
1161
1162 // handle device Ads
1163 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1164 final ProviderId provId = prov.getKey();
1165 final DeviceDescriptions lDeviceDescs = prov.getValue();
1166
1167 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1168
1169
1170 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1171 Timestamp advDevTimestamp = devAds.get(devFragId);
1172
1173 if (advDevTimestamp == null || lProvDevice.isNewer(advDevTimestamp)) {
1174 // remote does not have it or outdated, suggest
1175 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1176 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1177 // local is outdated, request
1178 reqDevices.add(devFragId);
1179 }
1180
1181 // handle port Ads
1182 for (Entry<PortNumber, Timestamped<PortDescription>>
1183 pe : lDeviceDescs.getPortDescs().entrySet()) {
1184
1185 final PortNumber num = pe.getKey();
1186 final Timestamped<PortDescription> lPort = pe.getValue();
1187
1188 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1189
1190 Timestamp advPortTimestamp = portAds.get(portFragId);
Yuta HIGUCHIec76bfe2014-10-09 20:17:07 -07001191 if (advPortTimestamp == null || lPort.isNewer(advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001192 // remote does not have it or outdated, suggest
1193 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1194 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1195 // local is outdated, request
1196 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1197 reqPorts.add(portFragId);
1198 }
1199
1200 // remove port Ad already processed
1201 portAds.remove(portFragId);
1202 } // end local port loop
1203
1204 // remove device Ad already processed
1205 devAds.remove(devFragId);
1206
1207 // find latest and update
1208 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1209 if (localLatest == null ||
1210 providerLatest.compareTo(localLatest) > 0) {
1211 localLatest = providerLatest;
1212 }
1213 } // end local provider loop
1214
1215 // checking if remote timestamp is more recent.
1216 Timestamp rOffline = offlineAds.get(deviceId);
1217 if (rOffline != null &&
1218 rOffline.compareTo(localLatest) > 0) {
1219 // remote offline timestamp suggests that the
1220 // device is off-line
1221 markOfflineInternal(deviceId, rOffline);
1222 }
1223
1224 Timestamp lOffline = offline.get(deviceId);
1225 if (lOffline != null && rOffline == null) {
1226 // locally offline, but remote is online, suggest offline
1227 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1228 }
1229
1230 // remove device offline Ad already processed
1231 offlineAds.remove(deviceId);
1232 } // end local device loop
1233 } // device lock
1234
1235 // If there is any Ads left, request them
1236 log.trace("Ads left {}, {}", devAds, portAds);
1237 reqDevices.addAll(devAds.keySet());
1238 reqPorts.addAll(portAds.keySet());
1239
1240 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1241 log.trace("Nothing to request to remote peer {}", sender);
1242 return;
1243 }
1244
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001245 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001246
1247 // 2-way Anti-Entropy for now
1248 try {
1249 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1250 } catch (IOException e) {
1251 log.error("Failed to send response advertisement to " + sender, e);
1252 }
1253
1254// Sketch of 3-way Anti-Entropy
1255// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1256// ClusterMessage message = new ClusterMessage(
1257// clusterService.getLocalNode().id(),
1258// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1259// SERIALIZER.encode(request));
1260//
1261// try {
1262// clusterCommunicator.unicast(message, advertisement.sender());
1263// } catch (IOException e) {
1264// log.error("Failed to send advertisement reply to "
1265// + advertisement.sender(), e);
1266// }
Madan Jampani47c93732014-10-06 20:46:08 -07001267 }
1268
Madan Jampani255a58b2014-10-09 12:08:20 -07001269 private void notifyDelegateIfNotNull(DeviceEvent event) {
1270 if (event != null) {
1271 notifyDelegate(event);
1272 }
1273 }
1274
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001275 private final class SendAdvertisementTask implements Runnable {
1276
1277 @Override
1278 public void run() {
1279 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001280 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001281 return;
1282 }
1283
1284 try {
1285 final NodeId self = clusterService.getLocalNode().id();
1286 Set<ControllerNode> nodes = clusterService.getNodes();
1287
1288 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1289 .transform(toNodeId())
1290 .toList();
1291
1292 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001293 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001294 return;
1295 }
1296
1297 NodeId peer;
1298 do {
1299 int idx = RandomUtils.nextInt(0, nodeIds.size());
1300 peer = nodeIds.get(idx);
1301 } while (peer.equals(self));
1302
1303 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1304
1305 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001306 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001307 return;
1308 }
1309
1310 try {
1311 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1312 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001313 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001314 return;
1315 }
1316 } catch (Exception e) {
1317 // catch all Exception to avoid Scheduled task being suppressed.
1318 log.error("Exception thrown while sending advertisement", e);
1319 }
1320 }
1321 }
1322
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001323 private final class InternalDeviceEventListener
1324 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001325 @Override
1326 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001327
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001328 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001329 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001330
Madan Jampani47c93732014-10-06 20:46:08 -07001331 ProviderId providerId = event.providerId();
1332 DeviceId deviceId = event.deviceId();
1333 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001334
Madan Jampani2af244a2015-02-22 13:12:01 -08001335 try {
1336 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1337 } catch (Exception e) {
1338 log.warn("Exception thrown handling device update", e);
1339 }
Madan Jampani47c93732014-10-06 20:46:08 -07001340 }
1341 }
1342
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001343 private final class InternalDeviceOfflineEventListener
1344 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001345 @Override
1346 public void handle(ClusterMessage message) {
1347
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001348 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001349 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001350
1351 DeviceId deviceId = event.deviceId();
1352 Timestamp timestamp = event.timestamp();
1353
Madan Jampani2af244a2015-02-22 13:12:01 -08001354 try {
1355 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1356 } catch (Exception e) {
1357 log.warn("Exception thrown handling device offline", e);
1358 }
Madan Jampani25322532014-10-08 11:20:38 -07001359 }
1360 }
1361
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001362 private final class InternalRemoveRequestListener
1363 implements ClusterMessageHandler {
1364 @Override
1365 public void handle(ClusterMessage message) {
1366 log.debug("Received device remove request from peer: {}", message.sender());
1367 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001368
Madan Jampani2af244a2015-02-22 13:12:01 -08001369 try {
1370 removeDevice(did);
1371 } catch (Exception e) {
1372 log.warn("Exception thrown handling device remove", e);
1373 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001374 }
1375 }
1376
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001377 private final class InternalDeviceRemovedEventListener
1378 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001379 @Override
1380 public void handle(ClusterMessage message) {
1381
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001382 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001383 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001384
1385 DeviceId deviceId = event.deviceId();
1386 Timestamp timestamp = event.timestamp();
1387
Madan Jampani2af244a2015-02-22 13:12:01 -08001388 try {
1389 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1390 } catch (Exception e) {
1391 log.warn("Exception thrown handling device removed", e);
1392 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001393 }
1394 }
1395
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001396 private final class InternalPortEventListener
1397 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001398 @Override
1399 public void handle(ClusterMessage message) {
1400
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001401 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001402 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001403
1404 ProviderId providerId = event.providerId();
1405 DeviceId deviceId = event.deviceId();
1406 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1407
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001408 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001409 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001410 // Note: dropped information will be recovered by anti-entropy
1411 return;
1412 }
1413
Madan Jampani2af244a2015-02-22 13:12:01 -08001414 try {
1415 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1416 } catch (Exception e) {
1417 log.warn("Exception thrown handling port update", e);
1418 }
Madan Jampani47c93732014-10-06 20:46:08 -07001419 }
1420 }
1421
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001422 private final class InternalPortStatusEventListener
1423 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001424 @Override
1425 public void handle(ClusterMessage message) {
1426
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001427 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001428 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001429
1430 ProviderId providerId = event.providerId();
1431 DeviceId deviceId = event.deviceId();
1432 Timestamped<PortDescription> portDescription = event.portDescription();
1433
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001434 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001435 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001436 // Note: dropped information will be recovered by anti-entropy
1437 return;
1438 }
1439
Madan Jampani2af244a2015-02-22 13:12:01 -08001440 try {
1441 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1442 } catch (Exception e) {
1443 log.warn("Exception thrown handling port update", e);
1444 }
Madan Jampani47c93732014-10-06 20:46:08 -07001445 }
1446 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001447
1448 private final class InternalDeviceAdvertisementListener
1449 implements ClusterMessageHandler {
1450
1451 @Override
1452 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001453 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001454 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001455 try {
1456 handleAdvertisement(advertisement);
1457 } catch (Exception e) {
1458 log.warn("Exception thrown handling Device advertisements.", e);
1459 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001460 }
1461 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001462
1463 private final class DeviceInjectedEventListener
1464 implements ClusterMessageHandler {
1465 @Override
1466 public void handle(ClusterMessage message) {
1467
1468 log.debug("Received injected device event from peer: {}", message.sender());
1469 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1470
1471 ProviderId providerId = event.providerId();
1472 DeviceId deviceId = event.deviceId();
1473 DeviceDescription deviceDescription = event.deviceDescription();
1474
Madan Jampani2af244a2015-02-22 13:12:01 -08001475 try {
1476 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1477 } catch (Exception e) {
1478 log.warn("Exception thrown handling device injected event.", e);
1479 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001480 }
1481 }
1482
1483 private final class PortInjectedEventListener
1484 implements ClusterMessageHandler {
1485 @Override
1486 public void handle(ClusterMessage message) {
1487
1488 log.debug("Received injected port event from peer: {}", message.sender());
1489 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1490
1491 ProviderId providerId = event.providerId();
1492 DeviceId deviceId = event.deviceId();
1493 List<PortDescription> portDescriptions = event.portDescriptions();
1494
Madan Jampani2af244a2015-02-22 13:12:01 -08001495 try {
1496 updatePorts(providerId, deviceId, portDescriptions);
1497 } catch (Exception e) {
1498 log.warn("Exception thrown handling port injected event.", e);
1499 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001500 }
1501 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001502}