blob: 0de64caa362812c7d8bcfbbbeafbf65dec58a721 [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 HIGUCHI60a190b2014-11-07 16:24:47 -080062import org.onlab.onos.store.serializers.impl.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 HIGUCHI91768e32014-11-22 05:06:35 -0800144 .register(DistributedStoreSerializers.STORE_COMMON)
145 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
146 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
147 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700148 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800149 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
150 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700151 .register(DeviceAntiEntropyAdvertisement.class)
152 .register(DeviceFragmentId.class)
153 .register(PortFragmentId.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800154 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700155 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700156 };
157
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700158 private ScheduledExecutorService executor;
159
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700160 @Activate
161 public void activate() {
Madan Jampani2206e012014-10-06 21:04:20 -0700162 clusterCommunicator.addSubscriber(
163 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener());
164 clusterCommunicator.addSubscriber(
Madan Jampani25322532014-10-08 11:20:38 -0700165 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, new InternalDeviceOfflineEventListener());
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800166 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ, new InternalRemoveRequestListener());
Madan Jampani25322532014-10-08 11:20:38 -0700167 clusterCommunicator.addSubscriber(
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700168 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener());
169 clusterCommunicator.addSubscriber(
Madan Jampani2206e012014-10-06 21:04:20 -0700170 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener());
171 clusterCommunicator.addSubscriber(
172 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700173 clusterCommunicator.addSubscriber(
174 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE, new InternalDeviceAdvertisementListener());
175
176 executor =
177 newSingleThreadScheduledExecutor(namedThreads("anti-entropy-%d"));
178
179 // TODO: Make these configurable
180 long initialDelaySec = 5;
181 long periodSec = 5;
182 // start anti-entropy thread
183 executor.scheduleAtFixedRate(new SendAdvertisementTask(),
184 initialDelaySec, periodSec, TimeUnit.SECONDS);
185
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700186 log.info("Started");
187 }
188
189 @Deactivate
190 public void deactivate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700191
192 executor.shutdownNow();
193 try {
194 boolean timedout = executor.awaitTermination(5, TimeUnit.SECONDS);
195 if (timedout) {
196 log.error("Timeout during executor shutdown");
197 }
198 } catch (InterruptedException e) {
199 log.error("Error during executor shutdown", e);
200 }
201
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700202 deviceDescs.clear();
203 devices.clear();
204 devicePorts.clear();
205 availableDevices.clear();
206 log.info("Stopped");
207 }
208
209 @Override
210 public int getDeviceCount() {
211 return devices.size();
212 }
213
214 @Override
215 public Iterable<Device> getDevices() {
216 return Collections.unmodifiableCollection(devices.values());
217 }
218
219 @Override
220 public Device getDevice(DeviceId deviceId) {
221 return devices.get(deviceId);
222 }
223
224 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700225 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
226 DeviceId deviceId,
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700227 DeviceDescription deviceDescription) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700228 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700229 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700230 final DeviceEvent event;
231 final Timestamped<DeviceDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800232 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
233 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700234 event = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800235 mergedDesc = device.get(providerId).getDeviceDesc();
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700236 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700237 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700238 log.info("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
239 providerId, deviceId);
240 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700241 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
Madan Jampani47c93732014-10-06 20:46:08 -0700242 } catch (IOException e) {
Madan Jampani25322532014-10-08 11:20:38 -0700243 log.error("Failed to notify peers of a device update topology event for providerId: "
Madan Jampani47c93732014-10-06 20:46:08 -0700244 + providerId + " and deviceId: " + deviceId, e);
245 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700246 }
247 return event;
248 }
249
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700250 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
251 DeviceId deviceId,
252 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700253
254 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800255 Map<ProviderId, DeviceDescriptions> device
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700256 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700257
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800258 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700259 // locking per device
260
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700261 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
262 log.debug("Ignoring outdated event: {}", deltaDesc);
263 return null;
264 }
265
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800266 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700267
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700268 final Device oldDevice = devices.get(deviceId);
269 final Device newDevice;
270
271 if (deltaDesc == descs.getDeviceDesc() ||
272 deltaDesc.isNewer(descs.getDeviceDesc())) {
273 // on new device or valid update
274 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800275 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700276 } else {
277 // outdated event, ignored.
278 return null;
279 }
280 if (oldDevice == null) {
281 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700282 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700283 } else {
284 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700285 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700286 }
287 }
288 }
289
290 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700291 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700292 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700293 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700294
295 // update composed device cache
296 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
297 verify(oldDevice == null,
298 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
299 providerId, oldDevice, newDevice);
300
301 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700302 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700303 }
304
305 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
306 }
307
308 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700309 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700310 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700311 Device oldDevice,
312 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700313 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700314 boolean propertiesChanged =
315 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
316 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion());
317 boolean annotationsChanged =
318 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700319
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700320 // Primary providers can respond to all changes, but ancillary ones
321 // should respond only to annotation changes.
322 if ((providerId.isAncillary() && annotationsChanged) ||
323 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700324 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
325 if (!replaced) {
326 verify(replaced,
327 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
328 providerId, oldDevice, devices.get(newDevice.id())
329 , newDevice);
330 }
331 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700332 markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700333 }
334 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
335 }
336
337 // Otherwise merely attempt to change availability if primary provider
338 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700339 boolean added = markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700340 return !added ? null :
341 new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null);
342 }
343 return null;
344 }
345
346 @Override
347 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700348 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700349 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700350 if (event != null) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700351 log.info("Notifying peers of a device offline topology event for deviceId: {} {}",
352 deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700353 try {
354 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
355 } catch (IOException e) {
356 log.error("Failed to notify peers of a device offline topology event for deviceId: {}",
357 deviceId);
358 }
359 }
360 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700361 }
362
363 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
364
365 Map<ProviderId, DeviceDescriptions> providerDescs
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700366 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700367
368 // locking device
369 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700370
371 // accept off-line if given timestamp is newer than
372 // the latest Timestamp from Primary provider
373 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
374 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
375 if (timestamp.compareTo(lastTimestamp) <= 0) {
376 // outdated event ignore
377 return null;
378 }
379
380 offline.put(deviceId, timestamp);
381
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700382 Device device = devices.get(deviceId);
383 if (device == null) {
384 return null;
385 }
386 boolean removed = availableDevices.remove(deviceId);
387 if (removed) {
388 // TODO: broadcast ... DOWN only?
389 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700390 }
391 return null;
392 }
393 }
394
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700395 /**
396 * Marks the device as available if the given timestamp is not outdated,
397 * compared to the time the device has been marked offline.
398 *
399 * @param deviceId identifier of the device
400 * @param timestamp of the event triggering this change.
401 * @return true if availability change request was accepted and changed the state
402 */
403 // Guarded by deviceDescs value (=Device lock)
404 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
405 // accept on-line if given timestamp is newer than
406 // the latest offline request Timestamp
407 Timestamp offlineTimestamp = offline.get(deviceId);
408 if (offlineTimestamp == null ||
409 offlineTimestamp.compareTo(timestamp) < 0) {
410
411 offline.remove(deviceId);
412 return availableDevices.add(deviceId);
413 }
414 return false;
415 }
416
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700417 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700418 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
419 DeviceId deviceId,
420 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700421
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700422 final Timestamp newTimestamp;
423 try {
424 newTimestamp = deviceClockService.getTimestamp(deviceId);
425 } catch (IllegalStateException e) {
426 log.info("Timestamp was not available for device {}", deviceId);
427 log.debug(" discarding {}", portDescriptions);
428 // Failed to generate timestamp.
429
430 // Possible situation:
431 // Device connected and became master for short period of time,
432 // but lost mastership before this instance had the chance to
433 // retrieve term information.
434
435 // Information dropped here is expected to be recoverable by
436 // device probing after mastership change
437
438 return Collections.emptyList();
439 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800440 log.debug("timestamp for {} {}", deviceId, newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700441
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700442 final Timestamped<List<PortDescription>> timestampedInput
443 = new Timestamped<>(portDescriptions, newTimestamp);
444 final List<DeviceEvent> events;
445 final Timestamped<List<PortDescription>> merged;
446
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800447 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
448 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700449 events = updatePortsInternal(providerId, deviceId, timestampedInput);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800450 final DeviceDescriptions descs = device.get(providerId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700451 List<PortDescription> mergedList =
452 FluentIterable.from(portDescriptions)
453 .transform(new Function<PortDescription, PortDescription>() {
454 @Override
455 public PortDescription apply(PortDescription input) {
456 // lookup merged port description
457 return descs.getPortDesc(input.portNumber()).value();
458 }
459 }).toList();
460 merged = new Timestamped<List<PortDescription>>(mergedList, newTimestamp);
461 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700462 if (!events.isEmpty()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800463 log.info("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Madan Jampani47c93732014-10-06 20:46:08 -0700464 providerId, deviceId);
465 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700466 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
Madan Jampani47c93732014-10-06 20:46:08 -0700467 } catch (IOException e) {
468 log.error("Failed to notify peers of a port update topology event or providerId: "
469 + providerId + " and deviceId: " + deviceId, e);
470 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700471 }
472 return events;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700473 }
474
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700475 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
476 DeviceId deviceId,
477 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700478
479 Device device = devices.get(deviceId);
480 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
481
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700482 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700483 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
484
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700485 List<DeviceEvent> events = new ArrayList<>();
486 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700487
488 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
489 log.debug("Ignoring outdated events: {}", portDescriptions);
490 return null;
491 }
492
493 DeviceDescriptions descs = descsMap.get(providerId);
494 // every provider must provide DeviceDescription.
495 checkArgument(descs != null,
496 "Device description for Device ID %s from Provider %s was not found",
497 deviceId, providerId);
498
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700499 Map<PortNumber, Port> ports = getPortMap(deviceId);
500
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700501 final Timestamp newTimestamp = portDescriptions.timestamp();
502
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700503 // Add new ports
504 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700505 for (PortDescription portDescription : portDescriptions.value()) {
506 final PortNumber number = portDescription.portNumber();
507 processed.add(number);
508
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700509 final Port oldPort = ports.get(number);
510 final Port newPort;
511
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700512
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700513 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
514 if (existingPortDesc == null ||
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700515 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700516 // on new port or valid update
517 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700518 descs.putPortDesc(new Timestamped<>(portDescription,
519 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700520 newPort = composePort(device, number, descsMap);
521 } else {
522 // outdated event, ignored.
523 continue;
524 }
525
526 events.add(oldPort == null ?
527 createPort(device, newPort, ports) :
528 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700529 }
530
531 events.addAll(pruneOldPorts(device, ports, processed));
532 }
533 return FluentIterable.from(events).filter(notNull()).toList();
534 }
535
536 // Creates a new port based on the port description adds it to the map and
537 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700538 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700539 private DeviceEvent createPort(Device device, Port newPort,
540 Map<PortNumber, Port> ports) {
541 ports.put(newPort.number(), newPort);
542 return new DeviceEvent(PORT_ADDED, device, newPort);
543 }
544
545 // Checks if the specified port requires update and if so, it replaces the
546 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700547 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700548 private DeviceEvent updatePort(Device device, Port oldPort,
549 Port newPort,
550 Map<PortNumber, Port> ports) {
551 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700552 oldPort.type() != newPort.type() ||
553 oldPort.portSpeed() != newPort.portSpeed() ||
554 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700555 ports.put(oldPort.number(), newPort);
556 return new DeviceEvent(PORT_UPDATED, device, newPort);
557 }
558 return null;
559 }
560
561 // Prunes the specified list of ports based on which ports are in the
562 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700563 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700564 private List<DeviceEvent> pruneOldPorts(Device device,
565 Map<PortNumber, Port> ports,
566 Set<PortNumber> processed) {
567 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700568 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700569 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700570 Entry<PortNumber, Port> e = iterator.next();
571 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700572 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700573 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700574 iterator.remove();
575 }
576 }
577 return events;
578 }
579
580 // Gets the map of ports for the specified device; if one does not already
581 // exist, it creates and registers a new one.
582 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
583 return createIfAbsentUnchecked(devicePorts, deviceId,
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700584 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
585 }
586
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700587 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700588 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700589 Map<ProviderId, DeviceDescriptions> r;
590 r = deviceDescs.get(deviceId);
591 if (r == null) {
592 r = new HashMap<ProviderId, DeviceDescriptions>();
593 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
594 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
595 if (concurrentlyAdded != null) {
596 r = concurrentlyAdded;
597 }
598 }
599 return r;
600 }
601
602 // Guarded by deviceDescs value (=Device lock)
603 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
604 Map<ProviderId, DeviceDescriptions> device,
605 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
606
607 synchronized (device) {
608 DeviceDescriptions r = device.get(providerId);
609 if (r == null) {
610 r = new DeviceDescriptions(deltaDesc);
611 device.put(providerId, r);
612 }
613 return r;
614 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700615 }
616
617 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700618 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
619 DeviceId deviceId,
620 PortDescription portDescription) {
621
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700622 final Timestamp newTimestamp;
623 try {
624 newTimestamp = deviceClockService.getTimestamp(deviceId);
625 } catch (IllegalStateException e) {
626 log.info("Timestamp was not available for device {}", deviceId);
627 log.debug(" discarding {}", portDescription);
628 // Failed to generate timestamp. Ignoring.
629 // See updatePorts comment
630 return null;
631 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700632 final Timestamped<PortDescription> deltaDesc
633 = new Timestamped<>(portDescription, newTimestamp);
634 final DeviceEvent event;
635 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800636 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
637 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700638 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800639 mergedDesc = device.get(providerId)
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700640 .getPortDesc(portDescription.portNumber());
641 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700642 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700643 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
644 providerId, deviceId);
645 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700646 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Madan Jampani47c93732014-10-06 20:46:08 -0700647 } catch (IOException e) {
648 log.error("Failed to notify peers of a port status update topology event or providerId: "
649 + providerId + " and deviceId: " + deviceId, e);
650 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700651 }
652 return event;
653 }
654
655 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
656 Timestamped<PortDescription> deltaDesc) {
657
658 Device device = devices.get(deviceId);
659 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
660
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700661 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700662 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
663
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700664 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700665
666 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
667 log.debug("Ignoring outdated event: {}", deltaDesc);
668 return null;
669 }
670
671 DeviceDescriptions descs = descsMap.get(providerId);
672 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700673 verify(descs != null,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700674 "Device description for Device ID %s from Provider %s was not found",
675 deviceId, providerId);
676
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700677 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
678 final PortNumber number = deltaDesc.value().portNumber();
679 final Port oldPort = ports.get(number);
680 final Port newPort;
681
682 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
683 if (existingPortDesc == null ||
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700684 deltaDesc.isNewer(existingPortDesc)) {
685 // on new port or valid update
686 // update description
687 descs.putPortDesc(deltaDesc);
688 newPort = composePort(device, number, descsMap);
689 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700690 // same or outdated event, ignored.
691 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700692 return null;
693 }
694
695 if (oldPort == null) {
696 return createPort(device, newPort, ports);
697 } else {
698 return updatePort(device, oldPort, newPort, ports);
699 }
700 }
701 }
702
703 @Override
704 public List<Port> getPorts(DeviceId deviceId) {
705 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
706 if (ports == null) {
707 return Collections.emptyList();
708 }
709 return ImmutableList.copyOf(ports.values());
710 }
711
712 @Override
713 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
714 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
715 return ports == null ? null : ports.get(portNumber);
716 }
717
718 @Override
719 public boolean isAvailable(DeviceId deviceId) {
720 return availableDevices.contains(deviceId);
721 }
722
723 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700724 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800725 final NodeId myId = clusterService.getLocalNode().id();
726 NodeId master = mastershipService.getMasterFor(deviceId);
727
728 // if there exist a master, forward
729 // if there is no master, try to become one and process
730
731 boolean relinquishAtEnd = false;
732 if (master == null) {
733 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
734 if (myRole != MastershipRole.NONE) {
735 relinquishAtEnd = true;
736 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800737 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800738 mastershipService.requestRoleFor(deviceId);
739 MastershipTermService termService = mastershipService.requestTermService();
740 MastershipTerm term = termService.getMastershipTerm(deviceId);
741 if (myId.equals(term.master())) {
742 master = myId;
743 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700744 }
745
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800746 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800747 log.debug("{} has control of {}, forwarding remove request",
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800748 master, deviceId);
749
750 ClusterMessage message = new ClusterMessage(
751 myId,
752 DEVICE_REMOVE_REQ,
753 SERIALIZER.encode(deviceId));
754
755 try {
756 clusterCommunicator.unicast(message, master);
757 } catch (IOException e) {
758 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
759 }
760
761 // event will be triggered after master processes it.
762 return null;
763 }
764
765 // I have control..
766
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700767 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700768 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700769 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800770 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700771 deviceId);
772 try {
773 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
774 } catch (IOException e) {
775 log.error("Failed to notify peers of a device removed topology event for deviceId: {}",
776 deviceId);
777 }
778 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800779 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800780 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800781 mastershipService.relinquishMastership(deviceId);
782 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700783 return event;
784 }
785
786 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
787 Timestamp timestamp) {
788
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700789 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700790 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700791 // accept removal request if given timestamp is newer than
792 // the latest Timestamp from Primary provider
793 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
794 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
795 if (timestamp.compareTo(lastTimestamp) <= 0) {
796 // outdated event ignore
797 return null;
798 }
799 removalRequest.put(deviceId, timestamp);
800
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700801 Device device = devices.remove(deviceId);
802 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700803 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
804 if (ports != null) {
805 ports.clear();
806 }
807 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700808 descs.clear();
809 return device == null ? null :
810 new DeviceEvent(DEVICE_REMOVED, device, null);
811 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700812 }
813
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700814 /**
815 * Checks if given timestamp is superseded by removal request
816 * with more recent timestamp.
817 *
818 * @param deviceId identifier of a device
819 * @param timestampToCheck timestamp of an event to check
820 * @return true if device is already removed
821 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700822 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
823 Timestamp removalTimestamp = removalRequest.get(deviceId);
824 if (removalTimestamp != null &&
825 removalTimestamp.compareTo(timestampToCheck) >= 0) {
826 // removalRequest is more recent
827 return true;
828 }
829 return false;
830 }
831
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700832 /**
833 * Returns a Device, merging description given from multiple Providers.
834 *
835 * @param deviceId device identifier
836 * @param providerDescs Collection of Descriptions from multiple providers
837 * @return Device instance
838 */
839 private Device composeDevice(DeviceId deviceId,
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700840 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700841
Thomas Vachuska444eda62014-10-28 13:09:42 -0700842 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700843
844 ProviderId primary = pickPrimaryPID(providerDescs);
845
846 DeviceDescriptions desc = providerDescs.get(primary);
847
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700848 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700849 Type type = base.type();
850 String manufacturer = base.manufacturer();
851 String hwVersion = base.hwVersion();
852 String swVersion = base.swVersion();
853 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700854 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700855 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
856 annotations = merge(annotations, base.annotations());
857
858 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
859 if (e.getKey().equals(primary)) {
860 continue;
861 }
862 // TODO: should keep track of Description timestamp
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700863 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700864 // Currently assuming there will never be a key conflict between
865 // providers
866
867 // annotation merging. not so efficient, should revisit later
868 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
869 }
870
871 return new DefaultDevice(primary, deviceId , type, manufacturer,
alshabib7911a052014-10-16 17:49:37 -0700872 hwVersion, swVersion, serialNumber,
873 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700874 }
875
876 /**
877 * Returns a Port, merging description given from multiple Providers.
878 *
879 * @param device device the port is on
880 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700881 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700882 * @return Port instance
883 */
884 private Port composePort(Device device, PortNumber number,
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700885 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700886
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700887 ProviderId primary = pickPrimaryPID(descsMap);
888 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700889 // if no primary, assume not enabled
890 // TODO: revisit this default port enabled/disabled behavior
891 boolean isEnabled = false;
892 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
893
894 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
895 if (portDesc != null) {
896 isEnabled = portDesc.value().isEnabled();
897 annotations = merge(annotations, portDesc.value().annotations());
898 }
899
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700900 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700901 if (e.getKey().equals(primary)) {
902 continue;
903 }
904 // TODO: should keep track of Description timestamp
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700905 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700906 // Currently assuming there will never be a key conflict between
907 // providers
908
909 // annotation merging. not so efficient, should revisit later
910 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
911 if (otherPortDesc != null) {
912 annotations = merge(annotations, otherPortDesc.value().annotations());
913 }
914 }
915
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700916 return portDesc == null ?
917 new DefaultPort(device, number, false, annotations) :
918 new DefaultPort(device, number, isEnabled, portDesc.value().type(),
919 portDesc.value().portSpeed(), annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700920 }
921
922 /**
923 * @return primary ProviderID, or randomly chosen one if none exists
924 */
925 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700926 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700927 ProviderId fallBackPrimary = null;
928 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
929 if (!e.getKey().isAncillary()) {
930 return e.getKey();
931 } else if (fallBackPrimary == null) {
932 // pick randomly as a fallback in case there is no primary
933 fallBackPrimary = e.getKey();
934 }
935 }
936 return fallBackPrimary;
937 }
938
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700939 private DeviceDescriptions getPrimaryDescriptions(
940 Map<ProviderId, DeviceDescriptions> providerDescs) {
941 ProviderId pid = pickPrimaryPID(providerDescs);
942 return providerDescs.get(pid);
943 }
944
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700945 // TODO: should we be throwing exception?
946 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
947 ClusterMessage message = new ClusterMessage(
948 clusterService.getLocalNode().id(),
949 subject,
950 SERIALIZER.encode(event));
951 clusterCommunicator.unicast(message, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700952 }
953
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700954 // TODO: should we be throwing exception?
955 private void broadcastMessage(MessageSubject subject, Object event) throws IOException {
956 ClusterMessage message = new ClusterMessage(
957 clusterService.getLocalNode().id(),
958 subject,
959 SERIALIZER.encode(event));
960 clusterCommunicator.broadcast(message);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700961 }
Madan Jampani47c93732014-10-06 20:46:08 -0700962
963 private void notifyPeers(InternalDeviceEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700964 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -0700965 }
966
Madan Jampani25322532014-10-08 11:20:38 -0700967 private void notifyPeers(InternalDeviceOfflineEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700968 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -0700969 }
970
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700971 private void notifyPeers(InternalDeviceRemovedEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700972 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700973 }
974
Madan Jampani47c93732014-10-06 20:46:08 -0700975 private void notifyPeers(InternalPortEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700976 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -0700977 }
978
979 private void notifyPeers(InternalPortStatusEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700980 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
981 }
982
983 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
984 try {
985 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
986 } catch (IOException e) {
987 log.error("Failed to send" + event + " to " + recipient, e);
988 }
989 }
990
991 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
992 try {
993 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
994 } catch (IOException e) {
995 log.error("Failed to send" + event + " to " + recipient, e);
996 }
997 }
998
999 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1000 try {
1001 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1002 } catch (IOException e) {
1003 log.error("Failed to send" + event + " to " + recipient, e);
1004 }
1005 }
1006
1007 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1008 try {
1009 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1010 } catch (IOException e) {
1011 log.error("Failed to send" + event + " to " + recipient, e);
1012 }
1013 }
1014
1015 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1016 try {
1017 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1018 } catch (IOException e) {
1019 log.error("Failed to send" + event + " to " + recipient, e);
1020 }
1021 }
1022
1023 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1024 final NodeId self = clusterService.getLocalNode().id();
1025
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001026 final int numDevices = deviceDescs.size();
1027 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1028 final int portsPerDevice = 8; // random factor to minimize reallocation
1029 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1030 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001031
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001032 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001033 provs : deviceDescs.entrySet()) {
1034
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001035 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001036 final DeviceId deviceId = provs.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001037 final Map<ProviderId, DeviceDescriptions> devDescs = provs.getValue();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001038 synchronized (devDescs) {
1039
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001040 // send device offline timestamp
1041 Timestamp lOffline = this.offline.get(deviceId);
1042 if (lOffline != null) {
1043 adOffline.put(deviceId, lOffline);
1044 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001045
1046 for (Entry<ProviderId, DeviceDescriptions>
1047 prov : devDescs.entrySet()) {
1048
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001049 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001050 final ProviderId provId = prov.getKey();
1051 final DeviceDescriptions descs = prov.getValue();
1052
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001053 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001054 descs.getDeviceDesc().timestamp());
1055
1056 for (Entry<PortNumber, Timestamped<PortDescription>>
1057 portDesc : descs.getPortDescs().entrySet()) {
1058
1059 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001060 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001061 portDesc.getValue().timestamp());
1062 }
1063 }
1064 }
1065 }
1066
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001067 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001068 }
1069
1070 /**
1071 * Responds to anti-entropy advertisement message.
1072 * <P>
1073 * Notify sender about out-dated information using regular replication message.
1074 * Send back advertisement to sender if not in sync.
1075 *
1076 * @param advertisement to respond to
1077 */
1078 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1079
1080 final NodeId sender = advertisement.sender();
1081
1082 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1083 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1084 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1085
1086 // Fragments to request
1087 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1088 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1089
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001090 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001091 final DeviceId deviceId = de.getKey();
1092 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1093
1094 synchronized (lDevice) {
1095 // latestTimestamp across provider
1096 // Note: can be null initially
1097 Timestamp localLatest = offline.get(deviceId);
1098
1099 // handle device Ads
1100 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1101 final ProviderId provId = prov.getKey();
1102 final DeviceDescriptions lDeviceDescs = prov.getValue();
1103
1104 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1105
1106
1107 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1108 Timestamp advDevTimestamp = devAds.get(devFragId);
1109
1110 if (advDevTimestamp == null || lProvDevice.isNewer(advDevTimestamp)) {
1111 // remote does not have it or outdated, suggest
1112 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1113 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1114 // local is outdated, request
1115 reqDevices.add(devFragId);
1116 }
1117
1118 // handle port Ads
1119 for (Entry<PortNumber, Timestamped<PortDescription>>
1120 pe : lDeviceDescs.getPortDescs().entrySet()) {
1121
1122 final PortNumber num = pe.getKey();
1123 final Timestamped<PortDescription> lPort = pe.getValue();
1124
1125 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1126
1127 Timestamp advPortTimestamp = portAds.get(portFragId);
Yuta HIGUCHIec76bfe2014-10-09 20:17:07 -07001128 if (advPortTimestamp == null || lPort.isNewer(advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001129 // remote does not have it or outdated, suggest
1130 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1131 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1132 // local is outdated, request
1133 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1134 reqPorts.add(portFragId);
1135 }
1136
1137 // remove port Ad already processed
1138 portAds.remove(portFragId);
1139 } // end local port loop
1140
1141 // remove device Ad already processed
1142 devAds.remove(devFragId);
1143
1144 // find latest and update
1145 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1146 if (localLatest == null ||
1147 providerLatest.compareTo(localLatest) > 0) {
1148 localLatest = providerLatest;
1149 }
1150 } // end local provider loop
1151
1152 // checking if remote timestamp is more recent.
1153 Timestamp rOffline = offlineAds.get(deviceId);
1154 if (rOffline != null &&
1155 rOffline.compareTo(localLatest) > 0) {
1156 // remote offline timestamp suggests that the
1157 // device is off-line
1158 markOfflineInternal(deviceId, rOffline);
1159 }
1160
1161 Timestamp lOffline = offline.get(deviceId);
1162 if (lOffline != null && rOffline == null) {
1163 // locally offline, but remote is online, suggest offline
1164 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1165 }
1166
1167 // remove device offline Ad already processed
1168 offlineAds.remove(deviceId);
1169 } // end local device loop
1170 } // device lock
1171
1172 // If there is any Ads left, request them
1173 log.trace("Ads left {}, {}", devAds, portAds);
1174 reqDevices.addAll(devAds.keySet());
1175 reqPorts.addAll(portAds.keySet());
1176
1177 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1178 log.trace("Nothing to request to remote peer {}", sender);
1179 return;
1180 }
1181
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001182 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001183
1184 // 2-way Anti-Entropy for now
1185 try {
1186 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1187 } catch (IOException e) {
1188 log.error("Failed to send response advertisement to " + sender, e);
1189 }
1190
1191// Sketch of 3-way Anti-Entropy
1192// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1193// ClusterMessage message = new ClusterMessage(
1194// clusterService.getLocalNode().id(),
1195// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1196// SERIALIZER.encode(request));
1197//
1198// try {
1199// clusterCommunicator.unicast(message, advertisement.sender());
1200// } catch (IOException e) {
1201// log.error("Failed to send advertisement reply to "
1202// + advertisement.sender(), e);
1203// }
Madan Jampani47c93732014-10-06 20:46:08 -07001204 }
1205
Madan Jampani255a58b2014-10-09 12:08:20 -07001206 private void notifyDelegateIfNotNull(DeviceEvent event) {
1207 if (event != null) {
1208 notifyDelegate(event);
1209 }
1210 }
1211
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001212 private final class SendAdvertisementTask implements Runnable {
1213
1214 @Override
1215 public void run() {
1216 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001217 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001218 return;
1219 }
1220
1221 try {
1222 final NodeId self = clusterService.getLocalNode().id();
1223 Set<ControllerNode> nodes = clusterService.getNodes();
1224
1225 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1226 .transform(toNodeId())
1227 .toList();
1228
1229 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001230 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001231 return;
1232 }
1233
1234 NodeId peer;
1235 do {
1236 int idx = RandomUtils.nextInt(0, nodeIds.size());
1237 peer = nodeIds.get(idx);
1238 } while (peer.equals(self));
1239
1240 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1241
1242 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001243 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001244 return;
1245 }
1246
1247 try {
1248 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1249 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001250 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001251 return;
1252 }
1253 } catch (Exception e) {
1254 // catch all Exception to avoid Scheduled task being suppressed.
1255 log.error("Exception thrown while sending advertisement", e);
1256 }
1257 }
1258 }
1259
Madan Jampani47c93732014-10-06 20:46:08 -07001260 private class InternalDeviceEventListener implements ClusterMessageHandler {
1261 @Override
1262 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001263
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001264 log.debug("Received device update event from peer: {}", message.sender());
Madan Jampani53e44e62014-10-07 12:39:51 -07001265 InternalDeviceEvent event = (InternalDeviceEvent) SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001266
Madan Jampani47c93732014-10-06 20:46:08 -07001267 ProviderId providerId = event.providerId();
1268 DeviceId deviceId = event.deviceId();
1269 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001270
Madan Jampani255a58b2014-10-09 12:08:20 -07001271 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
Madan Jampani47c93732014-10-06 20:46:08 -07001272 }
1273 }
1274
Madan Jampani25322532014-10-08 11:20:38 -07001275 private class InternalDeviceOfflineEventListener implements ClusterMessageHandler {
1276 @Override
1277 public void handle(ClusterMessage message) {
1278
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001279 log.debug("Received device offline event from peer: {}", message.sender());
Madan Jampani25322532014-10-08 11:20:38 -07001280 InternalDeviceOfflineEvent event = (InternalDeviceOfflineEvent) SERIALIZER.decode(message.payload());
1281
1282 DeviceId deviceId = event.deviceId();
1283 Timestamp timestamp = event.timestamp();
1284
Madan Jampani255a58b2014-10-09 12:08:20 -07001285 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -07001286 }
1287 }
1288
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001289 private final class InternalRemoveRequestListener
1290 implements ClusterMessageHandler {
1291 @Override
1292 public void handle(ClusterMessage message) {
1293 log.debug("Received device remove request from peer: {}", message.sender());
1294 DeviceId did = SERIALIZER.decode(message.payload());
1295 removeDevice(did);
1296 }
1297 }
1298
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001299 private class InternalDeviceRemovedEventListener implements ClusterMessageHandler {
1300 @Override
1301 public void handle(ClusterMessage message) {
1302
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001303 log.debug("Received device removed event from peer: {}", message.sender());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001304 InternalDeviceRemovedEvent event = (InternalDeviceRemovedEvent) SERIALIZER.decode(message.payload());
1305
1306 DeviceId deviceId = event.deviceId();
1307 Timestamp timestamp = event.timestamp();
1308
Madan Jampani255a58b2014-10-09 12:08:20 -07001309 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001310 }
1311 }
1312
Madan Jampani47c93732014-10-06 20:46:08 -07001313 private class InternalPortEventListener implements ClusterMessageHandler {
1314 @Override
1315 public void handle(ClusterMessage message) {
1316
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001317 log.debug("Received port update event from peer: {}", message.sender());
Madan Jampani53e44e62014-10-07 12:39:51 -07001318 InternalPortEvent event = (InternalPortEvent) SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001319
1320 ProviderId providerId = event.providerId();
1321 DeviceId deviceId = event.deviceId();
1322 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1323
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001324 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001325 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001326 // Note: dropped information will be recovered by anti-entropy
1327 return;
1328 }
1329
Madan Jampani255a58b2014-10-09 12:08:20 -07001330 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
Madan Jampani47c93732014-10-06 20:46:08 -07001331 }
1332 }
1333
1334 private class InternalPortStatusEventListener implements ClusterMessageHandler {
1335 @Override
1336 public void handle(ClusterMessage message) {
1337
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001338 log.debug("Received port status update event from peer: {}", message.sender());
Madan Jampani53e44e62014-10-07 12:39:51 -07001339 InternalPortStatusEvent event = (InternalPortStatusEvent) SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001340
1341 ProviderId providerId = event.providerId();
1342 DeviceId deviceId = event.deviceId();
1343 Timestamped<PortDescription> portDescription = event.portDescription();
1344
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001345 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001346 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001347 // Note: dropped information will be recovered by anti-entropy
1348 return;
1349 }
1350
Madan Jampani255a58b2014-10-09 12:08:20 -07001351 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
Madan Jampani47c93732014-10-06 20:46:08 -07001352 }
1353 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001354
1355 private final class InternalDeviceAdvertisementListener
1356 implements ClusterMessageHandler {
1357
1358 @Override
1359 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001360 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001361 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
1362 handleAdvertisement(advertisement);
1363 }
1364 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001365}