blob: bd5a04f98414ed279cc9a8be1c6d349d162f0877 [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 */
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070016package org.onlab.onos.store.device.impl;
17
Yuta HIGUCHI47c40882014-10-10 18:44:37 -070018import com.google.common.base.Function;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070019import com.google.common.collect.FluentIterable;
20import com.google.common.collect.ImmutableList;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -070021import com.google.common.collect.Maps;
22import com.google.common.collect.Sets;
Madan Jampani47c93732014-10-06 20:46:08 -070023
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;
Madan Jampani53e44e62014-10-07 12:39:51 -070031import org.onlab.onos.cluster.ClusterService;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070032import org.onlab.onos.cluster.ControllerNode;
33import org.onlab.onos.cluster.NodeId;
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -070034import org.onlab.onos.mastership.MastershipService;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -080035import org.onlab.onos.mastership.MastershipTerm;
36import org.onlab.onos.mastership.MastershipTermService;
Yuta HIGUCHI39ede6a2014-10-03 15:23:33 -070037import org.onlab.onos.net.AnnotationsUtil;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070038import org.onlab.onos.net.DefaultAnnotations;
39import org.onlab.onos.net.DefaultDevice;
40import org.onlab.onos.net.DefaultPort;
41import org.onlab.onos.net.Device;
42import org.onlab.onos.net.Device.Type;
43import org.onlab.onos.net.DeviceId;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -080044import org.onlab.onos.net.MastershipRole;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070045import org.onlab.onos.net.Port;
46import org.onlab.onos.net.PortNumber;
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -070047import org.onlab.onos.net.device.DeviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070048import org.onlab.onos.net.device.DeviceDescription;
49import org.onlab.onos.net.device.DeviceEvent;
50import org.onlab.onos.net.device.DeviceStore;
51import org.onlab.onos.net.device.DeviceStoreDelegate;
52import org.onlab.onos.net.device.PortDescription;
53import org.onlab.onos.net.provider.ProviderId;
54import org.onlab.onos.store.AbstractStore;
Yuta HIGUCHId40483d2014-10-09 15:20:30 -070055import org.onlab.onos.store.Timestamp;
Madan Jampani47c93732014-10-06 20:46:08 -070056import org.onlab.onos.store.cluster.messaging.ClusterCommunicationService;
57import org.onlab.onos.store.cluster.messaging.ClusterMessage;
58import org.onlab.onos.store.cluster.messaging.ClusterMessageHandler;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070059import org.onlab.onos.store.cluster.messaging.MessageSubject;
Yuta HIGUCHIeecee552014-10-16 14:09:01 -070060import org.onlab.onos.store.impl.Timestamped;
Madan Jampani53e44e62014-10-07 12:39:51 -070061import org.onlab.onos.store.serializers.KryoSerializer;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070062import org.onlab.onos.store.serializers.DistributedStoreSerializers;
alshabib7911a052014-10-16 17:49:37 -070063import org.onlab.packet.ChassisId;
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -070064import org.onlab.util.KryoNamespace;
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -070065import org.onlab.util.NewConcurrentHashMap;
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 HIGUCHI9ee60f62014-10-09 10:00:01 -070081import java.util.concurrent.ScheduledExecutorService;
82import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070083
84import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070085import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHIdc7374c2014-10-10 11:11:09 -070086import static org.onlab.onos.cluster.ControllerNodeToNodeId.toNodeId;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070087import static org.onlab.onos.net.device.DeviceEvent.Type.*;
88import static org.slf4j.LoggerFactory.getLogger;
89import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
90import static org.onlab.onos.net.DefaultAnnotations.merge;
91import static com.google.common.base.Verify.verify;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070092import static org.onlab.util.Tools.namedThreads;
93import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
94import static org.onlab.onos.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -080095import static org.onlab.onos.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070096
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -070097// TODO: give me a better name
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070098/**
99 * Manages inventory of infrastructure devices using gossip protocol to distribute
100 * information.
101 */
102@Component(immediate = true)
103@Service
104public class GossipDeviceStore
105 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
106 implements DeviceStore {
107
108 private final Logger log = getLogger(getClass());
109
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700110 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700111
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700112 // innerMap is used to lock a Device, thus instance should never be replaced.
113 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700114 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700115 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700116
117 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700118 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
119 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
120
121 // to be updated under Device lock
122 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
123 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700124
125 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700126 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700127
128 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700129 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700130
Madan Jampani47c93732014-10-06 20:46:08 -0700131 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
132 protected ClusterCommunicationService clusterCommunicator;
133
Madan Jampani53e44e62014-10-07 12:39:51 -0700134 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
135 protected ClusterService clusterService;
136
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700137 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
138 protected MastershipService mastershipService;
139
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700140 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700141 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700142 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700143 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700144 .register(DistributedStoreSerializers.COMMON)
145
Madan Jampanifef9b3a2014-10-07 18:38:17 -0700146 .register(InternalDeviceEvent.class, new InternalDeviceEventSerializer())
Madan Jampani25322532014-10-08 11:20:38 -0700147 .register(InternalDeviceOfflineEvent.class, new InternalDeviceOfflineEventSerializer())
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700148 .register(InternalDeviceRemovedEvent.class)
Madan Jampanifef9b3a2014-10-07 18:38:17 -0700149 .register(InternalPortEvent.class, new InternalPortEventSerializer())
150 .register(InternalPortStatusEvent.class, new InternalPortStatusEventSerializer())
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700151 .register(DeviceAntiEntropyAdvertisement.class)
152 .register(DeviceFragmentId.class)
153 .register(PortFragmentId.class)
Madan Jampani53e44e62014-10-07 12:39:51 -0700154 .build()
155 .populate(1);
156 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700157 };
158
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700159 private ScheduledExecutorService executor;
160
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700161 @Activate
162 public void activate() {
Madan Jampani2206e012014-10-06 21:04:20 -0700163 clusterCommunicator.addSubscriber(
164 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener());
165 clusterCommunicator.addSubscriber(
Madan Jampani25322532014-10-08 11:20:38 -0700166 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, new InternalDeviceOfflineEventListener());
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800167 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ, new InternalRemoveRequestListener());
Madan Jampani25322532014-10-08 11:20:38 -0700168 clusterCommunicator.addSubscriber(
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700169 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener());
170 clusterCommunicator.addSubscriber(
Madan Jampani2206e012014-10-06 21:04:20 -0700171 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener());
172 clusterCommunicator.addSubscriber(
173 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700174 clusterCommunicator.addSubscriber(
175 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE, new InternalDeviceAdvertisementListener());
176
177 executor =
178 newSingleThreadScheduledExecutor(namedThreads("anti-entropy-%d"));
179
180 // TODO: Make these configurable
181 long initialDelaySec = 5;
182 long periodSec = 5;
183 // start anti-entropy thread
184 executor.scheduleAtFixedRate(new SendAdvertisementTask(),
185 initialDelaySec, periodSec, TimeUnit.SECONDS);
186
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700187 log.info("Started");
188 }
189
190 @Deactivate
191 public void deactivate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700192
193 executor.shutdownNow();
194 try {
195 boolean timedout = executor.awaitTermination(5, TimeUnit.SECONDS);
196 if (timedout) {
197 log.error("Timeout during executor shutdown");
198 }
199 } catch (InterruptedException e) {
200 log.error("Error during executor shutdown", e);
201 }
202
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700203 deviceDescs.clear();
204 devices.clear();
205 devicePorts.clear();
206 availableDevices.clear();
207 log.info("Stopped");
208 }
209
210 @Override
211 public int getDeviceCount() {
212 return devices.size();
213 }
214
215 @Override
216 public Iterable<Device> getDevices() {
217 return Collections.unmodifiableCollection(devices.values());
218 }
219
220 @Override
221 public Device getDevice(DeviceId deviceId) {
222 return devices.get(deviceId);
223 }
224
225 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700226 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
227 DeviceId deviceId,
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700228 DeviceDescription deviceDescription) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700229 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700230 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700231 final DeviceEvent event;
232 final Timestamped<DeviceDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800233 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
234 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700235 event = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800236 mergedDesc = device.get(providerId).getDeviceDesc();
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700237 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700238 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700239 log.info("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
240 providerId, deviceId);
241 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700242 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
Madan Jampani47c93732014-10-06 20:46:08 -0700243 } catch (IOException e) {
Madan Jampani25322532014-10-08 11:20:38 -0700244 log.error("Failed to notify peers of a device update topology event for providerId: "
Madan Jampani47c93732014-10-06 20:46:08 -0700245 + providerId + " and deviceId: " + deviceId, e);
246 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700247 }
248 return event;
249 }
250
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700251 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
252 DeviceId deviceId,
253 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700254
255 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800256 Map<ProviderId, DeviceDescriptions> device
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700257 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700258
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800259 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700260 // locking per device
261
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700262 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
263 log.debug("Ignoring outdated event: {}", deltaDesc);
264 return null;
265 }
266
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800267 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700268
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700269 final Device oldDevice = devices.get(deviceId);
270 final Device newDevice;
271
272 if (deltaDesc == descs.getDeviceDesc() ||
273 deltaDesc.isNewer(descs.getDeviceDesc())) {
274 // on new device or valid update
275 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800276 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700277 } else {
278 // outdated event, ignored.
279 return null;
280 }
281 if (oldDevice == null) {
282 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700283 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700284 } else {
285 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700286 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700287 }
288 }
289 }
290
291 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700292 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700293 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700294 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700295
296 // update composed device cache
297 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
298 verify(oldDevice == null,
299 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
300 providerId, oldDevice, newDevice);
301
302 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700303 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700304 }
305
306 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
307 }
308
309 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700310 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700311 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700312 Device oldDevice,
313 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700314 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700315 boolean propertiesChanged =
316 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
317 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion());
318 boolean annotationsChanged =
319 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700320
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700321 // Primary providers can respond to all changes, but ancillary ones
322 // should respond only to annotation changes.
323 if ((providerId.isAncillary() && annotationsChanged) ||
324 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700325 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
326 if (!replaced) {
327 verify(replaced,
328 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
329 providerId, oldDevice, devices.get(newDevice.id())
330 , newDevice);
331 }
332 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700333 markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700334 }
335 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
336 }
337
338 // Otherwise merely attempt to change availability if primary provider
339 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700340 boolean added = markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700341 return !added ? null :
342 new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null);
343 }
344 return null;
345 }
346
347 @Override
348 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700349 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700350 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700351 if (event != null) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700352 log.info("Notifying peers of a device offline topology event for deviceId: {} {}",
353 deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700354 try {
355 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
356 } catch (IOException e) {
357 log.error("Failed to notify peers of a device offline topology event for deviceId: {}",
358 deviceId);
359 }
360 }
361 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700362 }
363
364 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
365
366 Map<ProviderId, DeviceDescriptions> providerDescs
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700367 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700368
369 // locking device
370 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700371
372 // accept off-line if given timestamp is newer than
373 // the latest Timestamp from Primary provider
374 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
375 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
376 if (timestamp.compareTo(lastTimestamp) <= 0) {
377 // outdated event ignore
378 return null;
379 }
380
381 offline.put(deviceId, timestamp);
382
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700383 Device device = devices.get(deviceId);
384 if (device == null) {
385 return null;
386 }
387 boolean removed = availableDevices.remove(deviceId);
388 if (removed) {
389 // TODO: broadcast ... DOWN only?
390 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700391 }
392 return null;
393 }
394 }
395
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700396 /**
397 * Marks the device as available if the given timestamp is not outdated,
398 * compared to the time the device has been marked offline.
399 *
400 * @param deviceId identifier of the device
401 * @param timestamp of the event triggering this change.
402 * @return true if availability change request was accepted and changed the state
403 */
404 // Guarded by deviceDescs value (=Device lock)
405 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
406 // accept on-line if given timestamp is newer than
407 // the latest offline request Timestamp
408 Timestamp offlineTimestamp = offline.get(deviceId);
409 if (offlineTimestamp == null ||
410 offlineTimestamp.compareTo(timestamp) < 0) {
411
412 offline.remove(deviceId);
413 return availableDevices.add(deviceId);
414 }
415 return false;
416 }
417
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700418 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700419 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
420 DeviceId deviceId,
421 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700422
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700423 final Timestamp newTimestamp;
424 try {
425 newTimestamp = deviceClockService.getTimestamp(deviceId);
426 } catch (IllegalStateException e) {
427 log.info("Timestamp was not available for device {}", deviceId);
428 log.debug(" discarding {}", portDescriptions);
429 // Failed to generate timestamp.
430
431 // Possible situation:
432 // Device connected and became master for short period of time,
433 // but lost mastership before this instance had the chance to
434 // retrieve term information.
435
436 // Information dropped here is expected to be recoverable by
437 // device probing after mastership change
438
439 return Collections.emptyList();
440 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700441 log.info("timestamp for {} {}", deviceId, newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700442
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700443 final Timestamped<List<PortDescription>> timestampedInput
444 = new Timestamped<>(portDescriptions, newTimestamp);
445 final List<DeviceEvent> events;
446 final Timestamped<List<PortDescription>> merged;
447
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800448 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
449 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700450 events = updatePortsInternal(providerId, deviceId, timestampedInput);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800451 final DeviceDescriptions descs = device.get(providerId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700452 List<PortDescription> mergedList =
453 FluentIterable.from(portDescriptions)
454 .transform(new Function<PortDescription, PortDescription>() {
455 @Override
456 public PortDescription apply(PortDescription input) {
457 // lookup merged port description
458 return descs.getPortDesc(input.portNumber()).value();
459 }
460 }).toList();
461 merged = new Timestamped<List<PortDescription>>(mergedList, newTimestamp);
462 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700463 if (!events.isEmpty()) {
Madan Jampani47c93732014-10-06 20:46:08 -0700464 log.info("Notifying peers of a port update topology event for providerId: {} and deviceId: {}",
465 providerId, deviceId);
466 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700467 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
Madan Jampani47c93732014-10-06 20:46:08 -0700468 } catch (IOException e) {
469 log.error("Failed to notify peers of a port update topology event or providerId: "
470 + providerId + " and deviceId: " + deviceId, e);
471 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700472 }
473 return events;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700474 }
475
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700476 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
477 DeviceId deviceId,
478 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700479
480 Device device = devices.get(deviceId);
481 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
482
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700483 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700484 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
485
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700486 List<DeviceEvent> events = new ArrayList<>();
487 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700488
489 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
490 log.debug("Ignoring outdated events: {}", portDescriptions);
491 return null;
492 }
493
494 DeviceDescriptions descs = descsMap.get(providerId);
495 // every provider must provide DeviceDescription.
496 checkArgument(descs != null,
497 "Device description for Device ID %s from Provider %s was not found",
498 deviceId, providerId);
499
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700500 Map<PortNumber, Port> ports = getPortMap(deviceId);
501
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700502 final Timestamp newTimestamp = portDescriptions.timestamp();
503
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700504 // Add new ports
505 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700506 for (PortDescription portDescription : portDescriptions.value()) {
507 final PortNumber number = portDescription.portNumber();
508 processed.add(number);
509
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700510 final Port oldPort = ports.get(number);
511 final Port newPort;
512
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700513
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700514 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
515 if (existingPortDesc == null ||
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700516 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700517 // on new port or valid update
518 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700519 descs.putPortDesc(new Timestamped<>(portDescription,
520 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700521 newPort = composePort(device, number, descsMap);
522 } else {
523 // outdated event, ignored.
524 continue;
525 }
526
527 events.add(oldPort == null ?
528 createPort(device, newPort, ports) :
529 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700530 }
531
532 events.addAll(pruneOldPorts(device, ports, processed));
533 }
534 return FluentIterable.from(events).filter(notNull()).toList();
535 }
536
537 // Creates a new port based on the port description adds it to the map and
538 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700539 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700540 private DeviceEvent createPort(Device device, Port newPort,
541 Map<PortNumber, Port> ports) {
542 ports.put(newPort.number(), newPort);
543 return new DeviceEvent(PORT_ADDED, device, newPort);
544 }
545
546 // Checks if the specified port requires update and if so, it replaces the
547 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700548 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700549 private DeviceEvent updatePort(Device device, Port oldPort,
550 Port newPort,
551 Map<PortNumber, Port> ports) {
552 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700553 oldPort.type() != newPort.type() ||
554 oldPort.portSpeed() != newPort.portSpeed() ||
555 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700556 ports.put(oldPort.number(), newPort);
557 return new DeviceEvent(PORT_UPDATED, device, newPort);
558 }
559 return null;
560 }
561
562 // Prunes the specified list of ports based on which ports are in the
563 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700564 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700565 private List<DeviceEvent> pruneOldPorts(Device device,
566 Map<PortNumber, Port> ports,
567 Set<PortNumber> processed) {
568 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700569 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700570 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700571 Entry<PortNumber, Port> e = iterator.next();
572 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700573 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700574 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700575 iterator.remove();
576 }
577 }
578 return events;
579 }
580
581 // Gets the map of ports for the specified device; if one does not already
582 // exist, it creates and registers a new one.
583 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
584 return createIfAbsentUnchecked(devicePorts, deviceId,
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700585 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
586 }
587
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700588 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700589 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700590 Map<ProviderId, DeviceDescriptions> r;
591 r = deviceDescs.get(deviceId);
592 if (r == null) {
593 r = new HashMap<ProviderId, DeviceDescriptions>();
594 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
595 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
596 if (concurrentlyAdded != null) {
597 r = concurrentlyAdded;
598 }
599 }
600 return r;
601 }
602
603 // Guarded by deviceDescs value (=Device lock)
604 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
605 Map<ProviderId, DeviceDescriptions> device,
606 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
607
608 synchronized (device) {
609 DeviceDescriptions r = device.get(providerId);
610 if (r == null) {
611 r = new DeviceDescriptions(deltaDesc);
612 device.put(providerId, r);
613 }
614 return r;
615 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700616 }
617
618 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700619 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
620 DeviceId deviceId,
621 PortDescription portDescription) {
622
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700623 final Timestamp newTimestamp;
624 try {
625 newTimestamp = deviceClockService.getTimestamp(deviceId);
626 } catch (IllegalStateException e) {
627 log.info("Timestamp was not available for device {}", deviceId);
628 log.debug(" discarding {}", portDescription);
629 // Failed to generate timestamp. Ignoring.
630 // See updatePorts comment
631 return null;
632 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700633 final Timestamped<PortDescription> deltaDesc
634 = new Timestamped<>(portDescription, newTimestamp);
635 final DeviceEvent event;
636 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800637 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
638 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700639 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800640 mergedDesc = device.get(providerId)
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700641 .getPortDesc(portDescription.portNumber());
642 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700643 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700644 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
645 providerId, deviceId);
646 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700647 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Madan Jampani47c93732014-10-06 20:46:08 -0700648 } catch (IOException e) {
649 log.error("Failed to notify peers of a port status update topology event or providerId: "
650 + providerId + " and deviceId: " + deviceId, e);
651 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700652 }
653 return event;
654 }
655
656 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
657 Timestamped<PortDescription> deltaDesc) {
658
659 Device device = devices.get(deviceId);
660 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
661
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700662 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700663 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
664
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700665 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700666
667 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
668 log.debug("Ignoring outdated event: {}", deltaDesc);
669 return null;
670 }
671
672 DeviceDescriptions descs = descsMap.get(providerId);
673 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700674 verify(descs != null,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700675 "Device description for Device ID %s from Provider %s was not found",
676 deviceId, providerId);
677
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700678 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
679 final PortNumber number = deltaDesc.value().portNumber();
680 final Port oldPort = ports.get(number);
681 final Port newPort;
682
683 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
684 if (existingPortDesc == null ||
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700685 deltaDesc.isNewer(existingPortDesc)) {
686 // on new port or valid update
687 // update description
688 descs.putPortDesc(deltaDesc);
689 newPort = composePort(device, number, descsMap);
690 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700691 // same or outdated event, ignored.
692 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700693 return null;
694 }
695
696 if (oldPort == null) {
697 return createPort(device, newPort, ports);
698 } else {
699 return updatePort(device, oldPort, newPort, ports);
700 }
701 }
702 }
703
704 @Override
705 public List<Port> getPorts(DeviceId deviceId) {
706 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
707 if (ports == null) {
708 return Collections.emptyList();
709 }
710 return ImmutableList.copyOf(ports.values());
711 }
712
713 @Override
714 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
715 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
716 return ports == null ? null : ports.get(portNumber);
717 }
718
719 @Override
720 public boolean isAvailable(DeviceId deviceId) {
721 return availableDevices.contains(deviceId);
722 }
723
724 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700725 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800726 final NodeId myId = clusterService.getLocalNode().id();
727 NodeId master = mastershipService.getMasterFor(deviceId);
728
729 // if there exist a master, forward
730 // if there is no master, try to become one and process
731
732 boolean relinquishAtEnd = false;
733 if (master == null) {
734 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
735 if (myRole != MastershipRole.NONE) {
736 relinquishAtEnd = true;
737 }
738 log.info("Temporarlily requesting role for {} to remove", deviceId);
739 mastershipService.requestRoleFor(deviceId);
740 MastershipTermService termService = mastershipService.requestTermService();
741 MastershipTerm term = termService.getMastershipTerm(deviceId);
742 if (myId.equals(term.master())) {
743 master = myId;
744 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700745 }
746
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800747 if (!myId.equals(master)) {
748 log.info("{} has control of {}, forwarding remove request",
749 master, deviceId);
750
751 ClusterMessage message = new ClusterMessage(
752 myId,
753 DEVICE_REMOVE_REQ,
754 SERIALIZER.encode(deviceId));
755
756 try {
757 clusterCommunicator.unicast(message, master);
758 } catch (IOException e) {
759 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
760 }
761
762 // event will be triggered after master processes it.
763 return null;
764 }
765
766 // I have control..
767
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700768 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700769 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700770 if (event != null) {
771 log.info("Notifying peers of a device removed topology event for deviceId: {}",
772 deviceId);
773 try {
774 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
775 } catch (IOException e) {
776 log.error("Failed to notify peers of a device removed topology event for deviceId: {}",
777 deviceId);
778 }
779 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800780 if (relinquishAtEnd) {
781 log.info("Relinquishing temporary role acquired for {}", deviceId);
782 mastershipService.relinquishMastership(deviceId);
783 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700784 return event;
785 }
786
787 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
788 Timestamp timestamp) {
789
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700790 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700791 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700792 // accept removal request if given timestamp is newer than
793 // the latest Timestamp from Primary provider
794 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
795 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
796 if (timestamp.compareTo(lastTimestamp) <= 0) {
797 // outdated event ignore
798 return null;
799 }
800 removalRequest.put(deviceId, timestamp);
801
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700802 Device device = devices.remove(deviceId);
803 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700804 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
805 if (ports != null) {
806 ports.clear();
807 }
808 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700809 descs.clear();
810 return device == null ? null :
811 new DeviceEvent(DEVICE_REMOVED, device, null);
812 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700813 }
814
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700815 /**
816 * Checks if given timestamp is superseded by removal request
817 * with more recent timestamp.
818 *
819 * @param deviceId identifier of a device
820 * @param timestampToCheck timestamp of an event to check
821 * @return true if device is already removed
822 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700823 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
824 Timestamp removalTimestamp = removalRequest.get(deviceId);
825 if (removalTimestamp != null &&
826 removalTimestamp.compareTo(timestampToCheck) >= 0) {
827 // removalRequest is more recent
828 return true;
829 }
830 return false;
831 }
832
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700833 /**
834 * Returns a Device, merging description given from multiple Providers.
835 *
836 * @param deviceId device identifier
837 * @param providerDescs Collection of Descriptions from multiple providers
838 * @return Device instance
839 */
840 private Device composeDevice(DeviceId deviceId,
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700841 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700842
Thomas Vachuska444eda62014-10-28 13:09:42 -0700843 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700844
845 ProviderId primary = pickPrimaryPID(providerDescs);
846
847 DeviceDescriptions desc = providerDescs.get(primary);
848
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700849 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700850 Type type = base.type();
851 String manufacturer = base.manufacturer();
852 String hwVersion = base.hwVersion();
853 String swVersion = base.swVersion();
854 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700855 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700856 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
857 annotations = merge(annotations, base.annotations());
858
859 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
860 if (e.getKey().equals(primary)) {
861 continue;
862 }
863 // TODO: should keep track of Description timestamp
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700864 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700865 // Currently assuming there will never be a key conflict between
866 // providers
867
868 // annotation merging. not so efficient, should revisit later
869 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
870 }
871
872 return new DefaultDevice(primary, deviceId , type, manufacturer,
alshabib7911a052014-10-16 17:49:37 -0700873 hwVersion, swVersion, serialNumber,
874 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700875 }
876
877 /**
878 * Returns a Port, merging description given from multiple Providers.
879 *
880 * @param device device the port is on
881 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700882 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700883 * @return Port instance
884 */
885 private Port composePort(Device device, PortNumber number,
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700886 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700887
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700888 ProviderId primary = pickPrimaryPID(descsMap);
889 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700890 // if no primary, assume not enabled
891 // TODO: revisit this default port enabled/disabled behavior
892 boolean isEnabled = false;
893 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
894
895 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
896 if (portDesc != null) {
897 isEnabled = portDesc.value().isEnabled();
898 annotations = merge(annotations, portDesc.value().annotations());
899 }
900
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700901 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700902 if (e.getKey().equals(primary)) {
903 continue;
904 }
905 // TODO: should keep track of Description timestamp
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700906 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700907 // Currently assuming there will never be a key conflict between
908 // providers
909
910 // annotation merging. not so efficient, should revisit later
911 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
912 if (otherPortDesc != null) {
913 annotations = merge(annotations, otherPortDesc.value().annotations());
914 }
915 }
916
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700917 return portDesc == null ?
918 new DefaultPort(device, number, false, annotations) :
919 new DefaultPort(device, number, isEnabled, portDesc.value().type(),
920 portDesc.value().portSpeed(), annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700921 }
922
923 /**
924 * @return primary ProviderID, or randomly chosen one if none exists
925 */
926 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700927 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700928 ProviderId fallBackPrimary = null;
929 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
930 if (!e.getKey().isAncillary()) {
931 return e.getKey();
932 } else if (fallBackPrimary == null) {
933 // pick randomly as a fallback in case there is no primary
934 fallBackPrimary = e.getKey();
935 }
936 }
937 return fallBackPrimary;
938 }
939
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700940 private DeviceDescriptions getPrimaryDescriptions(
941 Map<ProviderId, DeviceDescriptions> providerDescs) {
942 ProviderId pid = pickPrimaryPID(providerDescs);
943 return providerDescs.get(pid);
944 }
945
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700946 // TODO: should we be throwing exception?
947 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
948 ClusterMessage message = new ClusterMessage(
949 clusterService.getLocalNode().id(),
950 subject,
951 SERIALIZER.encode(event));
952 clusterCommunicator.unicast(message, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700953 }
954
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700955 // TODO: should we be throwing exception?
956 private void broadcastMessage(MessageSubject subject, Object event) throws IOException {
957 ClusterMessage message = new ClusterMessage(
958 clusterService.getLocalNode().id(),
959 subject,
960 SERIALIZER.encode(event));
961 clusterCommunicator.broadcast(message);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700962 }
Madan Jampani47c93732014-10-06 20:46:08 -0700963
964 private void notifyPeers(InternalDeviceEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700965 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -0700966 }
967
Madan Jampani25322532014-10-08 11:20:38 -0700968 private void notifyPeers(InternalDeviceOfflineEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700969 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -0700970 }
971
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700972 private void notifyPeers(InternalDeviceRemovedEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700973 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700974 }
975
Madan Jampani47c93732014-10-06 20:46:08 -0700976 private void notifyPeers(InternalPortEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700977 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -0700978 }
979
980 private void notifyPeers(InternalPortStatusEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700981 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
982 }
983
984 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
985 try {
986 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
987 } catch (IOException e) {
988 log.error("Failed to send" + event + " to " + recipient, e);
989 }
990 }
991
992 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
993 try {
994 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
995 } catch (IOException e) {
996 log.error("Failed to send" + event + " to " + recipient, e);
997 }
998 }
999
1000 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1001 try {
1002 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1003 } catch (IOException e) {
1004 log.error("Failed to send" + event + " to " + recipient, e);
1005 }
1006 }
1007
1008 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1009 try {
1010 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1011 } catch (IOException e) {
1012 log.error("Failed to send" + event + " to " + recipient, e);
1013 }
1014 }
1015
1016 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1017 try {
1018 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1019 } catch (IOException e) {
1020 log.error("Failed to send" + event + " to " + recipient, e);
1021 }
1022 }
1023
1024 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1025 final NodeId self = clusterService.getLocalNode().id();
1026
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001027 final int numDevices = deviceDescs.size();
1028 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1029 final int portsPerDevice = 8; // random factor to minimize reallocation
1030 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1031 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001032
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001033 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001034 provs : deviceDescs.entrySet()) {
1035
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001036 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001037 final DeviceId deviceId = provs.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001038 final Map<ProviderId, DeviceDescriptions> devDescs = provs.getValue();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001039 synchronized (devDescs) {
1040
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001041 // send device offline timestamp
1042 Timestamp lOffline = this.offline.get(deviceId);
1043 if (lOffline != null) {
1044 adOffline.put(deviceId, lOffline);
1045 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001046
1047 for (Entry<ProviderId, DeviceDescriptions>
1048 prov : devDescs.entrySet()) {
1049
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001050 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001051 final ProviderId provId = prov.getKey();
1052 final DeviceDescriptions descs = prov.getValue();
1053
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001054 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001055 descs.getDeviceDesc().timestamp());
1056
1057 for (Entry<PortNumber, Timestamped<PortDescription>>
1058 portDesc : descs.getPortDescs().entrySet()) {
1059
1060 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001061 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001062 portDesc.getValue().timestamp());
1063 }
1064 }
1065 }
1066 }
1067
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001068 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001069 }
1070
1071 /**
1072 * Responds to anti-entropy advertisement message.
1073 * <P>
1074 * Notify sender about out-dated information using regular replication message.
1075 * Send back advertisement to sender if not in sync.
1076 *
1077 * @param advertisement to respond to
1078 */
1079 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1080
1081 final NodeId sender = advertisement.sender();
1082
1083 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1084 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1085 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1086
1087 // Fragments to request
1088 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1089 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1090
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001091 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001092 final DeviceId deviceId = de.getKey();
1093 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1094
1095 synchronized (lDevice) {
1096 // latestTimestamp across provider
1097 // Note: can be null initially
1098 Timestamp localLatest = offline.get(deviceId);
1099
1100 // handle device Ads
1101 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1102 final ProviderId provId = prov.getKey();
1103 final DeviceDescriptions lDeviceDescs = prov.getValue();
1104
1105 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1106
1107
1108 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1109 Timestamp advDevTimestamp = devAds.get(devFragId);
1110
1111 if (advDevTimestamp == null || lProvDevice.isNewer(advDevTimestamp)) {
1112 // remote does not have it or outdated, suggest
1113 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1114 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1115 // local is outdated, request
1116 reqDevices.add(devFragId);
1117 }
1118
1119 // handle port Ads
1120 for (Entry<PortNumber, Timestamped<PortDescription>>
1121 pe : lDeviceDescs.getPortDescs().entrySet()) {
1122
1123 final PortNumber num = pe.getKey();
1124 final Timestamped<PortDescription> lPort = pe.getValue();
1125
1126 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1127
1128 Timestamp advPortTimestamp = portAds.get(portFragId);
Yuta HIGUCHIec76bfe2014-10-09 20:17:07 -07001129 if (advPortTimestamp == null || lPort.isNewer(advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001130 // remote does not have it or outdated, suggest
1131 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1132 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1133 // local is outdated, request
1134 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1135 reqPorts.add(portFragId);
1136 }
1137
1138 // remove port Ad already processed
1139 portAds.remove(portFragId);
1140 } // end local port loop
1141
1142 // remove device Ad already processed
1143 devAds.remove(devFragId);
1144
1145 // find latest and update
1146 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1147 if (localLatest == null ||
1148 providerLatest.compareTo(localLatest) > 0) {
1149 localLatest = providerLatest;
1150 }
1151 } // end local provider loop
1152
1153 // checking if remote timestamp is more recent.
1154 Timestamp rOffline = offlineAds.get(deviceId);
1155 if (rOffline != null &&
1156 rOffline.compareTo(localLatest) > 0) {
1157 // remote offline timestamp suggests that the
1158 // device is off-line
1159 markOfflineInternal(deviceId, rOffline);
1160 }
1161
1162 Timestamp lOffline = offline.get(deviceId);
1163 if (lOffline != null && rOffline == null) {
1164 // locally offline, but remote is online, suggest offline
1165 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1166 }
1167
1168 // remove device offline Ad already processed
1169 offlineAds.remove(deviceId);
1170 } // end local device loop
1171 } // device lock
1172
1173 // If there is any Ads left, request them
1174 log.trace("Ads left {}, {}", devAds, portAds);
1175 reqDevices.addAll(devAds.keySet());
1176 reqPorts.addAll(portAds.keySet());
1177
1178 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1179 log.trace("Nothing to request to remote peer {}", sender);
1180 return;
1181 }
1182
1183 log.info("Need to sync {} {}", reqDevices, reqPorts);
1184
1185 // 2-way Anti-Entropy for now
1186 try {
1187 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1188 } catch (IOException e) {
1189 log.error("Failed to send response advertisement to " + sender, e);
1190 }
1191
1192// Sketch of 3-way Anti-Entropy
1193// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1194// ClusterMessage message = new ClusterMessage(
1195// clusterService.getLocalNode().id(),
1196// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1197// SERIALIZER.encode(request));
1198//
1199// try {
1200// clusterCommunicator.unicast(message, advertisement.sender());
1201// } catch (IOException e) {
1202// log.error("Failed to send advertisement reply to "
1203// + advertisement.sender(), e);
1204// }
Madan Jampani47c93732014-10-06 20:46:08 -07001205 }
1206
Madan Jampani255a58b2014-10-09 12:08:20 -07001207 private void notifyDelegateIfNotNull(DeviceEvent event) {
1208 if (event != null) {
1209 notifyDelegate(event);
1210 }
1211 }
1212
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001213 private final class SendAdvertisementTask implements Runnable {
1214
1215 @Override
1216 public void run() {
1217 if (Thread.currentThread().isInterrupted()) {
1218 log.info("Interrupted, quitting");
1219 return;
1220 }
1221
1222 try {
1223 final NodeId self = clusterService.getLocalNode().id();
1224 Set<ControllerNode> nodes = clusterService.getNodes();
1225
1226 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1227 .transform(toNodeId())
1228 .toList();
1229
1230 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHI37083082014-10-13 10:38:38 -07001231 log.debug("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001232 return;
1233 }
1234
1235 NodeId peer;
1236 do {
1237 int idx = RandomUtils.nextInt(0, nodeIds.size());
1238 peer = nodeIds.get(idx);
1239 } while (peer.equals(self));
1240
1241 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1242
1243 if (Thread.currentThread().isInterrupted()) {
1244 log.info("Interrupted, quitting");
1245 return;
1246 }
1247
1248 try {
1249 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1250 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001251 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001252 return;
1253 }
1254 } catch (Exception e) {
1255 // catch all Exception to avoid Scheduled task being suppressed.
1256 log.error("Exception thrown while sending advertisement", e);
1257 }
1258 }
1259 }
1260
Madan Jampani47c93732014-10-06 20:46:08 -07001261 private class InternalDeviceEventListener implements ClusterMessageHandler {
1262 @Override
1263 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001264
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001265 log.debug("Received device update event from peer: {}", message.sender());
Madan Jampani53e44e62014-10-07 12:39:51 -07001266 InternalDeviceEvent event = (InternalDeviceEvent) SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001267
Madan Jampani47c93732014-10-06 20:46:08 -07001268 ProviderId providerId = event.providerId();
1269 DeviceId deviceId = event.deviceId();
1270 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001271
Madan Jampani255a58b2014-10-09 12:08:20 -07001272 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
Madan Jampani47c93732014-10-06 20:46:08 -07001273 }
1274 }
1275
Madan Jampani25322532014-10-08 11:20:38 -07001276 private class InternalDeviceOfflineEventListener implements ClusterMessageHandler {
1277 @Override
1278 public void handle(ClusterMessage message) {
1279
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001280 log.debug("Received device offline event from peer: {}", message.sender());
Madan Jampani25322532014-10-08 11:20:38 -07001281 InternalDeviceOfflineEvent event = (InternalDeviceOfflineEvent) SERIALIZER.decode(message.payload());
1282
1283 DeviceId deviceId = event.deviceId();
1284 Timestamp timestamp = event.timestamp();
1285
Madan Jampani255a58b2014-10-09 12:08:20 -07001286 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -07001287 }
1288 }
1289
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001290 private final class InternalRemoveRequestListener
1291 implements ClusterMessageHandler {
1292 @Override
1293 public void handle(ClusterMessage message) {
1294 log.debug("Received device remove request from peer: {}", message.sender());
1295 DeviceId did = SERIALIZER.decode(message.payload());
1296 removeDevice(did);
1297 }
1298 }
1299
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001300 private class InternalDeviceRemovedEventListener implements ClusterMessageHandler {
1301 @Override
1302 public void handle(ClusterMessage message) {
1303
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001304 log.debug("Received device removed event from peer: {}", message.sender());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001305 InternalDeviceRemovedEvent event = (InternalDeviceRemovedEvent) SERIALIZER.decode(message.payload());
1306
1307 DeviceId deviceId = event.deviceId();
1308 Timestamp timestamp = event.timestamp();
1309
Madan Jampani255a58b2014-10-09 12:08:20 -07001310 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001311 }
1312 }
1313
Madan Jampani47c93732014-10-06 20:46:08 -07001314 private class InternalPortEventListener implements ClusterMessageHandler {
1315 @Override
1316 public void handle(ClusterMessage message) {
1317
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001318 log.debug("Received port update event from peer: {}", message.sender());
Madan Jampani53e44e62014-10-07 12:39:51 -07001319 InternalPortEvent event = (InternalPortEvent) SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001320
1321 ProviderId providerId = event.providerId();
1322 DeviceId deviceId = event.deviceId();
1323 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1324
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001325 if (getDevice(deviceId) == null) {
1326 log.info("{} not found on this node yet, ignoring.", deviceId);
1327 // Note: dropped information will be recovered by anti-entropy
1328 return;
1329 }
1330
Madan Jampani255a58b2014-10-09 12:08:20 -07001331 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
Madan Jampani47c93732014-10-06 20:46:08 -07001332 }
1333 }
1334
1335 private class InternalPortStatusEventListener implements ClusterMessageHandler {
1336 @Override
1337 public void handle(ClusterMessage message) {
1338
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001339 log.debug("Received port status update event from peer: {}", message.sender());
Madan Jampani53e44e62014-10-07 12:39:51 -07001340 InternalPortStatusEvent event = (InternalPortStatusEvent) SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001341
1342 ProviderId providerId = event.providerId();
1343 DeviceId deviceId = event.deviceId();
1344 Timestamped<PortDescription> portDescription = event.portDescription();
1345
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001346 if (getDevice(deviceId) == null) {
1347 log.info("{} not found on this node yet, ignoring.", deviceId);
1348 // Note: dropped information will be recovered by anti-entropy
1349 return;
1350 }
1351
Madan Jampani255a58b2014-10-09 12:08:20 -07001352 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
Madan Jampani47c93732014-10-06 20:46:08 -07001353 }
1354 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001355
1356 private final class InternalDeviceAdvertisementListener
1357 implements ClusterMessageHandler {
1358
1359 @Override
1360 public void handle(ClusterMessage message) {
Yuta HIGUCHI9a0a1d12014-10-13 22:38:02 -07001361 log.debug("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001362 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
1363 handleAdvertisement(advertisement);
1364 }
1365 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001366}