blob: 602fd9f469021b0e468f4ae81e21f79424367660 [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() {
Madan Jampani2206e012014-10-06 21:04:20 -0700179 clusterCommunicator.addSubscriber(
180 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener());
181 clusterCommunicator.addSubscriber(
Madan Jampani25322532014-10-08 11:20:38 -0700182 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, new InternalDeviceOfflineEventListener());
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800183 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ, new InternalRemoveRequestListener());
Madan Jampani25322532014-10-08 11:20:38 -0700184 clusterCommunicator.addSubscriber(
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700185 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener());
186 clusterCommunicator.addSubscriber(
Madan Jampani2206e012014-10-06 21:04:20 -0700187 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener());
188 clusterCommunicator.addSubscriber(
189 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700190 clusterCommunicator.addSubscriber(
191 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE, new InternalDeviceAdvertisementListener());
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800192 clusterCommunicator.addSubscriber(
193 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener());
194 clusterCommunicator.addSubscriber(
195 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700196
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800197 executor = Executors.newCachedThreadPool(groupedThreads("onos/device", "fg-%d"));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800198
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800199 backgroundExecutor =
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800200 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700201
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700202 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800203 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700204 initialDelaySec, periodSec, TimeUnit.SECONDS);
205
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700206 log.info("Started");
207 }
208
209 @Deactivate
210 public void deactivate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700211
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800212 executor.shutdownNow();
213
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800214 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700215 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800216 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700217 log.error("Timeout during executor shutdown");
218 }
219 } catch (InterruptedException e) {
220 log.error("Error during executor shutdown", e);
221 }
222
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700223 deviceDescs.clear();
224 devices.clear();
225 devicePorts.clear();
226 availableDevices.clear();
227 log.info("Stopped");
228 }
229
230 @Override
231 public int getDeviceCount() {
232 return devices.size();
233 }
234
235 @Override
236 public Iterable<Device> getDevices() {
237 return Collections.unmodifiableCollection(devices.values());
238 }
239
240 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800241 public Iterable<Device> getAvailableDevices() {
242 return FluentIterable.from(getDevices())
243 .filter(new Predicate<Device>() {
244
245 @Override
246 public boolean apply(Device input) {
247 return isAvailable(input.id());
248 }
249 });
250 }
251
252 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700253 public Device getDevice(DeviceId deviceId) {
254 return devices.get(deviceId);
255 }
256
257 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700258 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
259 DeviceId deviceId,
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700260 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800261 NodeId localNode = clusterService.getLocalNode().id();
262 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
263
264 // Process device update only if we're the master,
265 // otherwise signal the actual master.
266 DeviceEvent deviceEvent = null;
267 if (localNode.equals(deviceNode)) {
268
269 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
270 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
271 final Timestamped<DeviceDescription> mergedDesc;
272 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
273
274 synchronized (device) {
275 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
276 mergedDesc = device.get(providerId).getDeviceDesc();
277 }
278
279 if (deviceEvent != null) {
280 log.info("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
281 providerId, deviceId);
282 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
283 }
284
285 } else {
286
287 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
288 providerId, deviceId, deviceDescription);
289 ClusterMessage clusterMessage = new ClusterMessage(localNode, DEVICE_INJECTED,
290 SERIALIZER.encode(deviceInjectedEvent));
291
292 try {
293 clusterCommunicator.unicast(clusterMessage, deviceNode);
294 } catch (IOException e) {
295 log.warn("Failed to process injected device id: {} desc: {} " +
296 "(cluster messaging failed: {})",
297 deviceId, deviceDescription, e);
298 }
299
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700300 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800301
302 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700303 }
304
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700305 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
306 DeviceId deviceId,
307 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700308
309 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800310 Map<ProviderId, DeviceDescriptions> device
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700311 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700312
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800313 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700314 // locking per device
315
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700316 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
317 log.debug("Ignoring outdated event: {}", deltaDesc);
318 return null;
319 }
320
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800321 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700322
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700323 final Device oldDevice = devices.get(deviceId);
324 final Device newDevice;
325
326 if (deltaDesc == descs.getDeviceDesc() ||
327 deltaDesc.isNewer(descs.getDeviceDesc())) {
328 // on new device or valid update
329 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800330 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700331 } else {
332 // outdated event, ignored.
333 return null;
334 }
335 if (oldDevice == null) {
336 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700337 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700338 } else {
339 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700340 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700341 }
342 }
343 }
344
345 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700346 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700347 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700348 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700349
350 // update composed device cache
351 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
352 verify(oldDevice == null,
353 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
354 providerId, oldDevice, newDevice);
355
356 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700357 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700358 }
359
360 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
361 }
362
363 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700364 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700365 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700366 Device oldDevice,
367 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700368 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700369 boolean propertiesChanged =
370 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
371 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion());
372 boolean annotationsChanged =
373 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700374
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700375 // Primary providers can respond to all changes, but ancillary ones
376 // should respond only to annotation changes.
377 if ((providerId.isAncillary() && annotationsChanged) ||
378 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700379 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
380 if (!replaced) {
381 verify(replaced,
382 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
383 providerId, oldDevice, devices.get(newDevice.id())
384 , newDevice);
385 }
386 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700387 markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700388 }
389 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
390 }
391
392 // Otherwise merely attempt to change availability if primary provider
393 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700394 boolean added = markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700395 return !added ? null :
396 new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null);
397 }
398 return null;
399 }
400
401 @Override
402 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700403 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700404 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700405 if (event != null) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700406 log.info("Notifying peers of a device offline topology event for deviceId: {} {}",
407 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800408 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700409 }
410 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700411 }
412
413 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
414
415 Map<ProviderId, DeviceDescriptions> providerDescs
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700416 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700417
418 // locking device
419 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700420
421 // accept off-line if given timestamp is newer than
422 // the latest Timestamp from Primary provider
423 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
424 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
425 if (timestamp.compareTo(lastTimestamp) <= 0) {
426 // outdated event ignore
427 return null;
428 }
429
430 offline.put(deviceId, timestamp);
431
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700432 Device device = devices.get(deviceId);
433 if (device == null) {
434 return null;
435 }
436 boolean removed = availableDevices.remove(deviceId);
437 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700438 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700439 }
440 return null;
441 }
442 }
443
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700444 /**
445 * Marks the device as available if the given timestamp is not outdated,
446 * compared to the time the device has been marked offline.
447 *
448 * @param deviceId identifier of the device
449 * @param timestamp of the event triggering this change.
450 * @return true if availability change request was accepted and changed the state
451 */
452 // Guarded by deviceDescs value (=Device lock)
453 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
454 // accept on-line if given timestamp is newer than
455 // the latest offline request Timestamp
456 Timestamp offlineTimestamp = offline.get(deviceId);
457 if (offlineTimestamp == null ||
458 offlineTimestamp.compareTo(timestamp) < 0) {
459
460 offline.remove(deviceId);
461 return availableDevices.add(deviceId);
462 }
463 return false;
464 }
465
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700466 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700467 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
468 DeviceId deviceId,
469 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700470
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800471 NodeId localNode = clusterService.getLocalNode().id();
472 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
473 // since it will trigger distributed store read.
474 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
475 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
476 // If we don't care much about topology performance, then it might be OK.
477 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700478
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800479 // Process port update only if we're the master of the device,
480 // otherwise signal the actual master.
481 List<DeviceEvent> deviceEvents = null;
482 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700483
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800484 final Timestamp newTimestamp;
485 try {
486 newTimestamp = deviceClockService.getTimestamp(deviceId);
487 } catch (IllegalStateException e) {
488 log.info("Timestamp was not available for device {}", deviceId);
489 log.debug(" discarding {}", portDescriptions);
490 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700491
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800492 // Possible situation:
493 // Device connected and became master for short period of time,
494 // but lost mastership before this instance had the chance to
495 // retrieve term information.
496
497 // Information dropped here is expected to be recoverable by
498 // device probing after mastership change
499
500 return Collections.emptyList();
501 }
502 log.debug("timestamp for {} {}", deviceId, newTimestamp);
503
504 final Timestamped<List<PortDescription>> timestampedInput
505 = new Timestamped<>(portDescriptions, newTimestamp);
506 final Timestamped<List<PortDescription>> merged;
507
508 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
509
510 synchronized (device) {
511 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
512 final DeviceDescriptions descs = device.get(providerId);
513 List<PortDescription> mergedList =
514 FluentIterable.from(portDescriptions)
515 .transform(new Function<PortDescription, PortDescription>() {
516 @Override
517 public PortDescription apply(PortDescription input) {
518 // lookup merged port description
519 return descs.getPortDesc(input.portNumber()).value();
520 }
521 }).toList();
522 merged = new Timestamped<List<PortDescription>>(mergedList, newTimestamp);
523 }
524
525 if (!deviceEvents.isEmpty()) {
526 log.info("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
527 providerId, deviceId);
528 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
529 }
530
531 } else {
532
533 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
534 ClusterMessage clusterMessage = new ClusterMessage(
535 localNode, PORT_INJECTED, SERIALIZER.encode(portInjectedEvent));
536 try {
537 clusterCommunicator.unicast(clusterMessage, deviceNode);
538 } catch (IOException e) {
539 log.warn("Failed to process injected ports of device id: {} " +
540 "(cluster messaging failed: {})",
541 deviceId, e);
542 }
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700543 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700544
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800545 return deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700546 }
547
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700548 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
549 DeviceId deviceId,
550 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700551
552 Device device = devices.get(deviceId);
553 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
554
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700555 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700556 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
557
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700558 List<DeviceEvent> events = new ArrayList<>();
559 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700560
561 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
562 log.debug("Ignoring outdated events: {}", portDescriptions);
563 return null;
564 }
565
566 DeviceDescriptions descs = descsMap.get(providerId);
567 // every provider must provide DeviceDescription.
568 checkArgument(descs != null,
569 "Device description for Device ID %s from Provider %s was not found",
570 deviceId, providerId);
571
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700572 Map<PortNumber, Port> ports = getPortMap(deviceId);
573
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700574 final Timestamp newTimestamp = portDescriptions.timestamp();
575
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700576 // Add new ports
577 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700578 for (PortDescription portDescription : portDescriptions.value()) {
579 final PortNumber number = portDescription.portNumber();
580 processed.add(number);
581
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700582 final Port oldPort = ports.get(number);
583 final Port newPort;
584
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700585
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700586 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
587 if (existingPortDesc == null ||
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700588 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700589 // on new port or valid update
590 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700591 descs.putPortDesc(new Timestamped<>(portDescription,
592 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700593 newPort = composePort(device, number, descsMap);
594 } else {
595 // outdated event, ignored.
596 continue;
597 }
598
599 events.add(oldPort == null ?
600 createPort(device, newPort, ports) :
601 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700602 }
603
604 events.addAll(pruneOldPorts(device, ports, processed));
605 }
606 return FluentIterable.from(events).filter(notNull()).toList();
607 }
608
609 // Creates a new port based on the port description adds it to the map and
610 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700611 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700612 private DeviceEvent createPort(Device device, Port newPort,
613 Map<PortNumber, Port> ports) {
614 ports.put(newPort.number(), newPort);
615 return new DeviceEvent(PORT_ADDED, device, newPort);
616 }
617
618 // Checks if the specified port requires update and if so, it replaces the
619 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700620 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700621 private DeviceEvent updatePort(Device device, Port oldPort,
622 Port newPort,
623 Map<PortNumber, Port> ports) {
624 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700625 oldPort.type() != newPort.type() ||
626 oldPort.portSpeed() != newPort.portSpeed() ||
627 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700628 ports.put(oldPort.number(), newPort);
629 return new DeviceEvent(PORT_UPDATED, device, newPort);
630 }
631 return null;
632 }
633
634 // Prunes the specified list of ports based on which ports are in the
635 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700636 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700637 private List<DeviceEvent> pruneOldPorts(Device device,
638 Map<PortNumber, Port> ports,
639 Set<PortNumber> processed) {
640 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700641 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700642 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700643 Entry<PortNumber, Port> e = iterator.next();
644 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700645 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700646 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700647 iterator.remove();
648 }
649 }
650 return events;
651 }
652
653 // Gets the map of ports for the specified device; if one does not already
654 // exist, it creates and registers a new one.
655 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
656 return createIfAbsentUnchecked(devicePorts, deviceId,
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700657 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
658 }
659
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700660 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700661 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700662 Map<ProviderId, DeviceDescriptions> r;
663 r = deviceDescs.get(deviceId);
664 if (r == null) {
665 r = new HashMap<ProviderId, DeviceDescriptions>();
666 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
667 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
668 if (concurrentlyAdded != null) {
669 r = concurrentlyAdded;
670 }
671 }
672 return r;
673 }
674
675 // Guarded by deviceDescs value (=Device lock)
676 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
677 Map<ProviderId, DeviceDescriptions> device,
678 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
679
680 synchronized (device) {
681 DeviceDescriptions r = device.get(providerId);
682 if (r == null) {
683 r = new DeviceDescriptions(deltaDesc);
684 device.put(providerId, r);
685 }
686 return r;
687 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700688 }
689
690 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700691 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
692 DeviceId deviceId,
693 PortDescription portDescription) {
694
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700695 final Timestamp newTimestamp;
696 try {
697 newTimestamp = deviceClockService.getTimestamp(deviceId);
698 } catch (IllegalStateException e) {
699 log.info("Timestamp was not available for device {}", deviceId);
700 log.debug(" discarding {}", portDescription);
701 // Failed to generate timestamp. Ignoring.
702 // See updatePorts comment
703 return null;
704 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700705 final Timestamped<PortDescription> deltaDesc
706 = new Timestamped<>(portDescription, newTimestamp);
707 final DeviceEvent event;
708 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800709 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
710 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700711 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800712 mergedDesc = device.get(providerId)
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700713 .getPortDesc(portDescription.portNumber());
714 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700715 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700716 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
717 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800718 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700719 }
720 return event;
721 }
722
723 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
724 Timestamped<PortDescription> deltaDesc) {
725
726 Device device = devices.get(deviceId);
727 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
728
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700729 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700730 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
731
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700732 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700733
734 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
735 log.debug("Ignoring outdated event: {}", deltaDesc);
736 return null;
737 }
738
739 DeviceDescriptions descs = descsMap.get(providerId);
740 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700741 verify(descs != null,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700742 "Device description for Device ID %s from Provider %s was not found",
743 deviceId, providerId);
744
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700745 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
746 final PortNumber number = deltaDesc.value().portNumber();
747 final Port oldPort = ports.get(number);
748 final Port newPort;
749
750 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
751 if (existingPortDesc == null ||
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700752 deltaDesc.isNewer(existingPortDesc)) {
753 // on new port or valid update
754 // update description
755 descs.putPortDesc(deltaDesc);
756 newPort = composePort(device, number, descsMap);
757 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700758 // same or outdated event, ignored.
759 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700760 return null;
761 }
762
763 if (oldPort == null) {
764 return createPort(device, newPort, ports);
765 } else {
766 return updatePort(device, oldPort, newPort, ports);
767 }
768 }
769 }
770
771 @Override
772 public List<Port> getPorts(DeviceId deviceId) {
773 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
774 if (ports == null) {
775 return Collections.emptyList();
776 }
777 return ImmutableList.copyOf(ports.values());
778 }
779
780 @Override
781 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
782 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
783 return ports == null ? null : ports.get(portNumber);
784 }
785
786 @Override
787 public boolean isAvailable(DeviceId deviceId) {
788 return availableDevices.contains(deviceId);
789 }
790
791 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700792 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800793 final NodeId myId = clusterService.getLocalNode().id();
794 NodeId master = mastershipService.getMasterFor(deviceId);
795
796 // if there exist a master, forward
797 // if there is no master, try to become one and process
798
799 boolean relinquishAtEnd = false;
800 if (master == null) {
801 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
802 if (myRole != MastershipRole.NONE) {
803 relinquishAtEnd = true;
804 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800805 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800806 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800807 MastershipTerm term = termService.getMastershipTerm(deviceId);
808 if (myId.equals(term.master())) {
809 master = myId;
810 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700811 }
812
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800813 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800814 log.debug("{} has control of {}, forwarding remove request",
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800815 master, deviceId);
816
817 ClusterMessage message = new ClusterMessage(
818 myId,
819 DEVICE_REMOVE_REQ,
820 SERIALIZER.encode(deviceId));
821
822 try {
823 clusterCommunicator.unicast(message, master);
824 } catch (IOException e) {
825 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
826 }
827
828 // event will be triggered after master processes it.
829 return null;
830 }
831
832 // I have control..
833
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700834 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700835 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700836 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800837 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700838 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800839 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700840 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800841 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800842 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800843 mastershipService.relinquishMastership(deviceId);
844 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700845 return event;
846 }
847
848 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
849 Timestamp timestamp) {
850
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700851 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700852 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700853 // accept removal request if given timestamp is newer than
854 // the latest Timestamp from Primary provider
855 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
856 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
857 if (timestamp.compareTo(lastTimestamp) <= 0) {
858 // outdated event ignore
859 return null;
860 }
861 removalRequest.put(deviceId, timestamp);
862
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700863 Device device = devices.remove(deviceId);
864 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700865 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
866 if (ports != null) {
867 ports.clear();
868 }
869 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700870 descs.clear();
871 return device == null ? null :
872 new DeviceEvent(DEVICE_REMOVED, device, null);
873 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700874 }
875
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700876 /**
877 * Checks if given timestamp is superseded by removal request
878 * with more recent timestamp.
879 *
880 * @param deviceId identifier of a device
881 * @param timestampToCheck timestamp of an event to check
882 * @return true if device is already removed
883 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700884 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
885 Timestamp removalTimestamp = removalRequest.get(deviceId);
886 if (removalTimestamp != null &&
887 removalTimestamp.compareTo(timestampToCheck) >= 0) {
888 // removalRequest is more recent
889 return true;
890 }
891 return false;
892 }
893
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700894 /**
895 * Returns a Device, merging description given from multiple Providers.
896 *
897 * @param deviceId device identifier
898 * @param providerDescs Collection of Descriptions from multiple providers
899 * @return Device instance
900 */
901 private Device composeDevice(DeviceId deviceId,
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700902 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700903
Thomas Vachuska444eda62014-10-28 13:09:42 -0700904 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700905
906 ProviderId primary = pickPrimaryPID(providerDescs);
907
908 DeviceDescriptions desc = providerDescs.get(primary);
909
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700910 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700911 Type type = base.type();
912 String manufacturer = base.manufacturer();
913 String hwVersion = base.hwVersion();
914 String swVersion = base.swVersion();
915 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700916 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700917 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
918 annotations = merge(annotations, base.annotations());
919
920 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
921 if (e.getKey().equals(primary)) {
922 continue;
923 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800924 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700925 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700926 // Currently assuming there will never be a key conflict between
927 // providers
928
929 // annotation merging. not so efficient, should revisit later
930 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
931 }
932
933 return new DefaultDevice(primary, deviceId , type, manufacturer,
alshabib7911a052014-10-16 17:49:37 -0700934 hwVersion, swVersion, serialNumber,
935 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700936 }
937
938 /**
939 * Returns a Port, merging description given from multiple Providers.
940 *
941 * @param device device the port is on
942 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700943 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700944 * @return Port instance
945 */
946 private Port composePort(Device device, PortNumber number,
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700947 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700948
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700949 ProviderId primary = pickPrimaryPID(descsMap);
950 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700951 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700952 boolean isEnabled = false;
953 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
954
955 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
956 if (portDesc != null) {
957 isEnabled = portDesc.value().isEnabled();
958 annotations = merge(annotations, portDesc.value().annotations());
959 }
960
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700961 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700962 if (e.getKey().equals(primary)) {
963 continue;
964 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800965 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700966 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700967 // Currently assuming there will never be a key conflict between
968 // providers
969
970 // annotation merging. not so efficient, should revisit later
971 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
972 if (otherPortDesc != null) {
973 annotations = merge(annotations, otherPortDesc.value().annotations());
974 }
975 }
976
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700977 return portDesc == null ?
978 new DefaultPort(device, number, false, annotations) :
979 new DefaultPort(device, number, isEnabled, portDesc.value().type(),
980 portDesc.value().portSpeed(), annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700981 }
982
983 /**
984 * @return primary ProviderID, or randomly chosen one if none exists
985 */
986 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700987 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700988 ProviderId fallBackPrimary = null;
989 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
990 if (!e.getKey().isAncillary()) {
991 return e.getKey();
992 } else if (fallBackPrimary == null) {
993 // pick randomly as a fallback in case there is no primary
994 fallBackPrimary = e.getKey();
995 }
996 }
997 return fallBackPrimary;
998 }
999
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001000 private DeviceDescriptions getPrimaryDescriptions(
1001 Map<ProviderId, DeviceDescriptions> providerDescs) {
1002 ProviderId pid = pickPrimaryPID(providerDescs);
1003 return providerDescs.get(pid);
1004 }
1005
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001006 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
1007 ClusterMessage message = new ClusterMessage(
1008 clusterService.getLocalNode().id(),
1009 subject,
1010 SERIALIZER.encode(event));
1011 clusterCommunicator.unicast(message, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001012 }
1013
Jonathan Hart7d656f42015-01-27 14:07:23 -08001014 private void broadcastMessage(MessageSubject subject, Object event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001015 ClusterMessage message = new ClusterMessage(
1016 clusterService.getLocalNode().id(),
1017 subject,
1018 SERIALIZER.encode(event));
1019 clusterCommunicator.broadcast(message);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001020 }
Madan Jampani47c93732014-10-06 20:46:08 -07001021
Jonathan Hart7d656f42015-01-27 14:07:23 -08001022 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001023 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001024 }
1025
Jonathan Hart7d656f42015-01-27 14:07:23 -08001026 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001027 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001028 }
1029
Jonathan Hart7d656f42015-01-27 14:07:23 -08001030 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001031 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001032 }
1033
Jonathan Hart7d656f42015-01-27 14:07:23 -08001034 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001035 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001036 }
1037
Jonathan Hart7d656f42015-01-27 14:07:23 -08001038 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001039 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1040 }
1041
1042 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1043 try {
1044 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1045 } catch (IOException e) {
1046 log.error("Failed to send" + event + " to " + recipient, e);
1047 }
1048 }
1049
1050 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1051 try {
1052 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1053 } catch (IOException e) {
1054 log.error("Failed to send" + event + " to " + recipient, e);
1055 }
1056 }
1057
1058 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1059 try {
1060 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1061 } catch (IOException e) {
1062 log.error("Failed to send" + event + " to " + recipient, e);
1063 }
1064 }
1065
1066 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1067 try {
1068 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1069 } catch (IOException e) {
1070 log.error("Failed to send" + event + " to " + recipient, e);
1071 }
1072 }
1073
1074 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1075 try {
1076 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1077 } catch (IOException e) {
1078 log.error("Failed to send" + event + " to " + recipient, e);
1079 }
1080 }
1081
1082 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1083 final NodeId self = clusterService.getLocalNode().id();
1084
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001085 final int numDevices = deviceDescs.size();
1086 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1087 final int portsPerDevice = 8; // random factor to minimize reallocation
1088 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1089 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001090
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001091 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001092
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001093 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001094 synchronized (devDescs) {
1095
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001096 // send device offline timestamp
1097 Timestamp lOffline = this.offline.get(deviceId);
1098 if (lOffline != null) {
1099 adOffline.put(deviceId, lOffline);
1100 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001101
1102 for (Entry<ProviderId, DeviceDescriptions>
1103 prov : devDescs.entrySet()) {
1104
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001105 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001106 final ProviderId provId = prov.getKey();
1107 final DeviceDescriptions descs = prov.getValue();
1108
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001109 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001110 descs.getDeviceDesc().timestamp());
1111
1112 for (Entry<PortNumber, Timestamped<PortDescription>>
1113 portDesc : descs.getPortDescs().entrySet()) {
1114
1115 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001116 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001117 portDesc.getValue().timestamp());
1118 }
1119 }
1120 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001121 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001122
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001123 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001124 }
1125
1126 /**
1127 * Responds to anti-entropy advertisement message.
1128 * <P>
1129 * Notify sender about out-dated information using regular replication message.
1130 * Send back advertisement to sender if not in sync.
1131 *
1132 * @param advertisement to respond to
1133 */
1134 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1135
1136 final NodeId sender = advertisement.sender();
1137
1138 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1139 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1140 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1141
1142 // Fragments to request
1143 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1144 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1145
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001146 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001147 final DeviceId deviceId = de.getKey();
1148 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1149
1150 synchronized (lDevice) {
1151 // latestTimestamp across provider
1152 // Note: can be null initially
1153 Timestamp localLatest = offline.get(deviceId);
1154
1155 // handle device Ads
1156 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1157 final ProviderId provId = prov.getKey();
1158 final DeviceDescriptions lDeviceDescs = prov.getValue();
1159
1160 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1161
1162
1163 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1164 Timestamp advDevTimestamp = devAds.get(devFragId);
1165
1166 if (advDevTimestamp == null || lProvDevice.isNewer(advDevTimestamp)) {
1167 // remote does not have it or outdated, suggest
1168 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1169 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1170 // local is outdated, request
1171 reqDevices.add(devFragId);
1172 }
1173
1174 // handle port Ads
1175 for (Entry<PortNumber, Timestamped<PortDescription>>
1176 pe : lDeviceDescs.getPortDescs().entrySet()) {
1177
1178 final PortNumber num = pe.getKey();
1179 final Timestamped<PortDescription> lPort = pe.getValue();
1180
1181 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1182
1183 Timestamp advPortTimestamp = portAds.get(portFragId);
Yuta HIGUCHIec76bfe2014-10-09 20:17:07 -07001184 if (advPortTimestamp == null || lPort.isNewer(advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001185 // remote does not have it or outdated, suggest
1186 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1187 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1188 // local is outdated, request
1189 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1190 reqPorts.add(portFragId);
1191 }
1192
1193 // remove port Ad already processed
1194 portAds.remove(portFragId);
1195 } // end local port loop
1196
1197 // remove device Ad already processed
1198 devAds.remove(devFragId);
1199
1200 // find latest and update
1201 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1202 if (localLatest == null ||
1203 providerLatest.compareTo(localLatest) > 0) {
1204 localLatest = providerLatest;
1205 }
1206 } // end local provider loop
1207
1208 // checking if remote timestamp is more recent.
1209 Timestamp rOffline = offlineAds.get(deviceId);
1210 if (rOffline != null &&
1211 rOffline.compareTo(localLatest) > 0) {
1212 // remote offline timestamp suggests that the
1213 // device is off-line
1214 markOfflineInternal(deviceId, rOffline);
1215 }
1216
1217 Timestamp lOffline = offline.get(deviceId);
1218 if (lOffline != null && rOffline == null) {
1219 // locally offline, but remote is online, suggest offline
1220 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1221 }
1222
1223 // remove device offline Ad already processed
1224 offlineAds.remove(deviceId);
1225 } // end local device loop
1226 } // device lock
1227
1228 // If there is any Ads left, request them
1229 log.trace("Ads left {}, {}", devAds, portAds);
1230 reqDevices.addAll(devAds.keySet());
1231 reqPorts.addAll(portAds.keySet());
1232
1233 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1234 log.trace("Nothing to request to remote peer {}", sender);
1235 return;
1236 }
1237
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001238 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001239
1240 // 2-way Anti-Entropy for now
1241 try {
1242 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1243 } catch (IOException e) {
1244 log.error("Failed to send response advertisement to " + sender, e);
1245 }
1246
1247// Sketch of 3-way Anti-Entropy
1248// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1249// ClusterMessage message = new ClusterMessage(
1250// clusterService.getLocalNode().id(),
1251// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1252// SERIALIZER.encode(request));
1253//
1254// try {
1255// clusterCommunicator.unicast(message, advertisement.sender());
1256// } catch (IOException e) {
1257// log.error("Failed to send advertisement reply to "
1258// + advertisement.sender(), e);
1259// }
Madan Jampani47c93732014-10-06 20:46:08 -07001260 }
1261
Madan Jampani255a58b2014-10-09 12:08:20 -07001262 private void notifyDelegateIfNotNull(DeviceEvent event) {
1263 if (event != null) {
1264 notifyDelegate(event);
1265 }
1266 }
1267
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001268 private final class SendAdvertisementTask implements Runnable {
1269
1270 @Override
1271 public void run() {
1272 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001273 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001274 return;
1275 }
1276
1277 try {
1278 final NodeId self = clusterService.getLocalNode().id();
1279 Set<ControllerNode> nodes = clusterService.getNodes();
1280
1281 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1282 .transform(toNodeId())
1283 .toList();
1284
1285 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001286 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001287 return;
1288 }
1289
1290 NodeId peer;
1291 do {
1292 int idx = RandomUtils.nextInt(0, nodeIds.size());
1293 peer = nodeIds.get(idx);
1294 } while (peer.equals(self));
1295
1296 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1297
1298 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001299 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001300 return;
1301 }
1302
1303 try {
1304 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1305 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001306 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001307 return;
1308 }
1309 } catch (Exception e) {
1310 // catch all Exception to avoid Scheduled task being suppressed.
1311 log.error("Exception thrown while sending advertisement", e);
1312 }
1313 }
1314 }
1315
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001316 private final class InternalDeviceEventListener
1317 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001318 @Override
1319 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001320
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001321 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001322 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001323
Madan Jampani47c93732014-10-06 20:46:08 -07001324 ProviderId providerId = event.providerId();
1325 DeviceId deviceId = event.deviceId();
1326 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001327
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001328 executor.submit(new Runnable() {
1329
1330 @Override
1331 public void run() {
1332 try {
1333 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1334 } catch (Exception e) {
1335 log.warn("Exception thrown handling device update", e);
1336 }
1337 }
1338 });
Madan Jampani47c93732014-10-06 20:46:08 -07001339 }
1340 }
1341
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001342 private final class InternalDeviceOfflineEventListener
1343 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001344 @Override
1345 public void handle(ClusterMessage message) {
1346
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001347 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001348 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001349
1350 DeviceId deviceId = event.deviceId();
1351 Timestamp timestamp = event.timestamp();
1352
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001353 executor.submit(new Runnable() {
1354
1355 @Override
1356 public void run() {
1357 try {
1358 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1359 } catch (Exception e) {
1360 log.warn("Exception thrown handling device offline", e);
1361 }
1362 }
1363 });
Madan Jampani25322532014-10-08 11:20:38 -07001364 }
1365 }
1366
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001367 private final class InternalRemoveRequestListener
1368 implements ClusterMessageHandler {
1369 @Override
1370 public void handle(ClusterMessage message) {
1371 log.debug("Received device remove request from peer: {}", message.sender());
1372 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001373
1374 executor.submit(new Runnable() {
1375
1376 @Override
1377 public void run() {
1378 try {
1379 removeDevice(did);
1380 } catch (Exception e) {
1381 log.warn("Exception thrown handling device remove", e);
1382 }
1383 }
1384 });
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001385 }
1386 }
1387
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001388 private final class InternalDeviceRemovedEventListener
1389 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001390 @Override
1391 public void handle(ClusterMessage message) {
1392
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001393 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001394 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001395
1396 DeviceId deviceId = event.deviceId();
1397 Timestamp timestamp = event.timestamp();
1398
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001399 executor.submit(new Runnable() {
1400
1401 @Override
1402 public void run() {
1403 try {
1404 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1405 } catch (Exception e) {
1406 log.warn("Exception thrown handling device removed", e);
1407 }
1408 }
1409 });
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001410 }
1411 }
1412
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001413 private final class InternalPortEventListener
1414 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001415 @Override
1416 public void handle(ClusterMessage message) {
1417
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001418 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001419 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001420
1421 ProviderId providerId = event.providerId();
1422 DeviceId deviceId = event.deviceId();
1423 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1424
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001425 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001426 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001427 // Note: dropped information will be recovered by anti-entropy
1428 return;
1429 }
1430
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001431 executor.submit(new Runnable() {
1432
1433 @Override
1434 public void run() {
1435 try {
1436 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1437 } catch (Exception e) {
1438 log.warn("Exception thrown handling port update", e);
1439 }
1440 }
1441 });
Madan Jampani47c93732014-10-06 20:46:08 -07001442 }
1443 }
1444
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001445 private final class InternalPortStatusEventListener
1446 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001447 @Override
1448 public void handle(ClusterMessage message) {
1449
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001450 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001451 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001452
1453 ProviderId providerId = event.providerId();
1454 DeviceId deviceId = event.deviceId();
1455 Timestamped<PortDescription> portDescription = event.portDescription();
1456
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001457 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001458 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001459 // Note: dropped information will be recovered by anti-entropy
1460 return;
1461 }
1462
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001463 executor.submit(new Runnable() {
1464
1465 @Override
1466 public void run() {
1467 try {
1468 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1469 } catch (Exception e) {
1470 log.warn("Exception thrown handling port update", e);
1471 }
1472 }
1473 });
Madan Jampani47c93732014-10-06 20:46:08 -07001474 }
1475 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001476
1477 private final class InternalDeviceAdvertisementListener
1478 implements ClusterMessageHandler {
1479
1480 @Override
1481 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001482 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001483 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Yuta HIGUCHI06586272014-11-25 14:27:03 -08001484 backgroundExecutor.submit(new Runnable() {
1485
1486 @Override
1487 public void run() {
1488 try {
1489 handleAdvertisement(advertisement);
1490 } catch (Exception e) {
1491 log.warn("Exception thrown handling Device advertisements.", e);
1492 }
1493 }
1494 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001495 }
1496 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001497
1498 private final class DeviceInjectedEventListener
1499 implements ClusterMessageHandler {
1500 @Override
1501 public void handle(ClusterMessage message) {
1502
1503 log.debug("Received injected device event from peer: {}", message.sender());
1504 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1505
1506 ProviderId providerId = event.providerId();
1507 DeviceId deviceId = event.deviceId();
1508 DeviceDescription deviceDescription = event.deviceDescription();
1509
1510 executor.submit(new Runnable() {
1511
1512 @Override
1513 public void run() {
1514 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1515 }
1516 });
1517 }
1518 }
1519
1520 private final class PortInjectedEventListener
1521 implements ClusterMessageHandler {
1522 @Override
1523 public void handle(ClusterMessage message) {
1524
1525 log.debug("Received injected port event from peer: {}", message.sender());
1526 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1527
1528 ProviderId providerId = event.providerId();
1529 DeviceId deviceId = event.deviceId();
1530 List<PortDescription> portDescriptions = event.portDescriptions();
1531
1532 executor.submit(new Runnable() {
1533
1534 @Override
1535 public void run() {
1536 updatePorts(providerId, deviceId, portDescriptions);
1537 }
1538 });
1539 }
1540 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001541}