blob: 19dc3e3fb2671a999a5ef7bad7285803499835ba [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 HIGUCHIbf71dff2014-10-14 16:02:33 -0700233 synchronized (getOrCreateDeviceDescriptionsMap(deviceId)) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700234 event = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700235 mergedDesc = getOrCreateDeviceDescriptionsMap(deviceId).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 HIGUCHIbf71dff2014-10-14 16:02:33 -0700255 Map<ProviderId, DeviceDescriptions> providerDescs
256 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700257
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700258 synchronized (providerDescs) {
259 // 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 HIGUCHIbf71dff2014-10-14 16:02:33 -0700266 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(providerDescs, 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);
275 newDevice = composeDevice(deviceId, providerDescs);
276 } 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 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700440 log.info("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 HIGUCHIbf71dff2014-10-14 16:02:33 -0700447 synchronized (getOrCreateDeviceDescriptionsMap(deviceId)) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700448 events = updatePortsInternal(providerId, deviceId, timestampedInput);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700449 final DeviceDescriptions descs = getOrCreateDeviceDescriptionsMap(deviceId).get(providerId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700450 List<PortDescription> mergedList =
451 FluentIterable.from(portDescriptions)
452 .transform(new Function<PortDescription, PortDescription>() {
453 @Override
454 public PortDescription apply(PortDescription input) {
455 // lookup merged port description
456 return descs.getPortDesc(input.portNumber()).value();
457 }
458 }).toList();
459 merged = new Timestamped<List<PortDescription>>(mergedList, newTimestamp);
460 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700461 if (!events.isEmpty()) {
Madan Jampani47c93732014-10-06 20:46:08 -0700462 log.info("Notifying peers of a port update topology event for providerId: {} and deviceId: {}",
463 providerId, deviceId);
464 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700465 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
Madan Jampani47c93732014-10-06 20:46:08 -0700466 } catch (IOException e) {
467 log.error("Failed to notify peers of a port update topology event or providerId: "
468 + providerId + " and deviceId: " + deviceId, e);
469 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700470 }
471 return events;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700472 }
473
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700474 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
475 DeviceId deviceId,
476 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700477
478 Device device = devices.get(deviceId);
479 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
480
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700481 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700482 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
483
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700484 List<DeviceEvent> events = new ArrayList<>();
485 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700486
487 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
488 log.debug("Ignoring outdated events: {}", portDescriptions);
489 return null;
490 }
491
492 DeviceDescriptions descs = descsMap.get(providerId);
493 // every provider must provide DeviceDescription.
494 checkArgument(descs != null,
495 "Device description for Device ID %s from Provider %s was not found",
496 deviceId, providerId);
497
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700498 Map<PortNumber, Port> ports = getPortMap(deviceId);
499
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700500 final Timestamp newTimestamp = portDescriptions.timestamp();
501
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700502 // Add new ports
503 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700504 for (PortDescription portDescription : portDescriptions.value()) {
505 final PortNumber number = portDescription.portNumber();
506 processed.add(number);
507
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700508 final Port oldPort = ports.get(number);
509 final Port newPort;
510
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700511
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700512 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
513 if (existingPortDesc == null ||
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700514 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700515 // on new port or valid update
516 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700517 descs.putPortDesc(new Timestamped<>(portDescription,
518 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700519 newPort = composePort(device, number, descsMap);
520 } else {
521 // outdated event, ignored.
522 continue;
523 }
524
525 events.add(oldPort == null ?
526 createPort(device, newPort, ports) :
527 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700528 }
529
530 events.addAll(pruneOldPorts(device, ports, processed));
531 }
532 return FluentIterable.from(events).filter(notNull()).toList();
533 }
534
535 // Creates a new port based on the port description adds it to the map and
536 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700537 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700538 private DeviceEvent createPort(Device device, Port newPort,
539 Map<PortNumber, Port> ports) {
540 ports.put(newPort.number(), newPort);
541 return new DeviceEvent(PORT_ADDED, device, newPort);
542 }
543
544 // Checks if the specified port requires update and if so, it replaces the
545 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700546 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700547 private DeviceEvent updatePort(Device device, Port oldPort,
548 Port newPort,
549 Map<PortNumber, Port> ports) {
550 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700551 oldPort.type() != newPort.type() ||
552 oldPort.portSpeed() != newPort.portSpeed() ||
553 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700554 ports.put(oldPort.number(), newPort);
555 return new DeviceEvent(PORT_UPDATED, device, newPort);
556 }
557 return null;
558 }
559
560 // Prunes the specified list of ports based on which ports are in the
561 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700562 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700563 private List<DeviceEvent> pruneOldPorts(Device device,
564 Map<PortNumber, Port> ports,
565 Set<PortNumber> processed) {
566 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700567 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700568 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700569 Entry<PortNumber, Port> e = iterator.next();
570 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700571 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700572 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700573 iterator.remove();
574 }
575 }
576 return events;
577 }
578
579 // Gets the map of ports for the specified device; if one does not already
580 // exist, it creates and registers a new one.
581 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
582 return createIfAbsentUnchecked(devicePorts, deviceId,
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700583 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
584 }
585
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700586 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700587 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700588 Map<ProviderId, DeviceDescriptions> r;
589 r = deviceDescs.get(deviceId);
590 if (r == null) {
591 r = new HashMap<ProviderId, DeviceDescriptions>();
592 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
593 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
594 if (concurrentlyAdded != null) {
595 r = concurrentlyAdded;
596 }
597 }
598 return r;
599 }
600
601 // Guarded by deviceDescs value (=Device lock)
602 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
603 Map<ProviderId, DeviceDescriptions> device,
604 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
605
606 synchronized (device) {
607 DeviceDescriptions r = device.get(providerId);
608 if (r == null) {
609 r = new DeviceDescriptions(deltaDesc);
610 device.put(providerId, r);
611 }
612 return r;
613 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700614 }
615
616 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700617 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
618 DeviceId deviceId,
619 PortDescription portDescription) {
620
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700621 final Timestamp newTimestamp;
622 try {
623 newTimestamp = deviceClockService.getTimestamp(deviceId);
624 } catch (IllegalStateException e) {
625 log.info("Timestamp was not available for device {}", deviceId);
626 log.debug(" discarding {}", portDescription);
627 // Failed to generate timestamp. Ignoring.
628 // See updatePorts comment
629 return null;
630 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700631 final Timestamped<PortDescription> deltaDesc
632 = new Timestamped<>(portDescription, newTimestamp);
633 final DeviceEvent event;
634 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700635 synchronized (getOrCreateDeviceDescriptionsMap(deviceId)) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700636 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700637 mergedDesc = getOrCreateDeviceDescriptionsMap(deviceId).get(providerId)
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700638 .getPortDesc(portDescription.portNumber());
639 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700640 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700641 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
642 providerId, deviceId);
643 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700644 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Madan Jampani47c93732014-10-06 20:46:08 -0700645 } catch (IOException e) {
646 log.error("Failed to notify peers of a port status update topology event or providerId: "
647 + providerId + " and deviceId: " + deviceId, e);
648 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700649 }
650 return event;
651 }
652
653 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
654 Timestamped<PortDescription> deltaDesc) {
655
656 Device device = devices.get(deviceId);
657 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
658
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700659 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700660 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
661
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700662 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700663
664 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
665 log.debug("Ignoring outdated event: {}", deltaDesc);
666 return null;
667 }
668
669 DeviceDescriptions descs = descsMap.get(providerId);
670 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700671 verify(descs != null,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700672 "Device description for Device ID %s from Provider %s was not found",
673 deviceId, providerId);
674
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700675 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
676 final PortNumber number = deltaDesc.value().portNumber();
677 final Port oldPort = ports.get(number);
678 final Port newPort;
679
680 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
681 if (existingPortDesc == null ||
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700682 deltaDesc.isNewer(existingPortDesc)) {
683 // on new port or valid update
684 // update description
685 descs.putPortDesc(deltaDesc);
686 newPort = composePort(device, number, descsMap);
687 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700688 // same or outdated event, ignored.
689 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700690 return null;
691 }
692
693 if (oldPort == null) {
694 return createPort(device, newPort, ports);
695 } else {
696 return updatePort(device, oldPort, newPort, ports);
697 }
698 }
699 }
700
701 @Override
702 public List<Port> getPorts(DeviceId deviceId) {
703 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
704 if (ports == null) {
705 return Collections.emptyList();
706 }
707 return ImmutableList.copyOf(ports.values());
708 }
709
710 @Override
711 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
712 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
713 return ports == null ? null : ports.get(portNumber);
714 }
715
716 @Override
717 public boolean isAvailable(DeviceId deviceId) {
718 return availableDevices.contains(deviceId);
719 }
720
721 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700722 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800723 final NodeId myId = clusterService.getLocalNode().id();
724 NodeId master = mastershipService.getMasterFor(deviceId);
725
726 // if there exist a master, forward
727 // if there is no master, try to become one and process
728
729 boolean relinquishAtEnd = false;
730 if (master == null) {
731 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
732 if (myRole != MastershipRole.NONE) {
733 relinquishAtEnd = true;
734 }
735 log.info("Temporarlily requesting role for {} to remove", deviceId);
736 mastershipService.requestRoleFor(deviceId);
737 MastershipTermService termService = mastershipService.requestTermService();
738 MastershipTerm term = termService.getMastershipTerm(deviceId);
739 if (myId.equals(term.master())) {
740 master = myId;
741 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700742 }
743
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800744 if (!myId.equals(master)) {
745 log.info("{} has control of {}, forwarding remove request",
746 master, deviceId);
747
748 ClusterMessage message = new ClusterMessage(
749 myId,
750 DEVICE_REMOVE_REQ,
751 SERIALIZER.encode(deviceId));
752
753 try {
754 clusterCommunicator.unicast(message, master);
755 } catch (IOException e) {
756 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
757 }
758
759 // event will be triggered after master processes it.
760 return null;
761 }
762
763 // I have control..
764
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700765 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700766 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700767 if (event != null) {
768 log.info("Notifying peers of a device removed topology event for deviceId: {}",
769 deviceId);
770 try {
771 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
772 } catch (IOException e) {
773 log.error("Failed to notify peers of a device removed topology event for deviceId: {}",
774 deviceId);
775 }
776 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800777 if (relinquishAtEnd) {
778 log.info("Relinquishing temporary role acquired for {}", deviceId);
779 mastershipService.relinquishMastership(deviceId);
780 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700781 return event;
782 }
783
784 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
785 Timestamp timestamp) {
786
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700787 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700788 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700789 // accept removal request if given timestamp is newer than
790 // the latest Timestamp from Primary provider
791 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
792 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
793 if (timestamp.compareTo(lastTimestamp) <= 0) {
794 // outdated event ignore
795 return null;
796 }
797 removalRequest.put(deviceId, timestamp);
798
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700799 Device device = devices.remove(deviceId);
800 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700801 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
802 if (ports != null) {
803 ports.clear();
804 }
805 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700806 descs.clear();
807 return device == null ? null :
808 new DeviceEvent(DEVICE_REMOVED, device, null);
809 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700810 }
811
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700812 /**
813 * Checks if given timestamp is superseded by removal request
814 * with more recent timestamp.
815 *
816 * @param deviceId identifier of a device
817 * @param timestampToCheck timestamp of an event to check
818 * @return true if device is already removed
819 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700820 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
821 Timestamp removalTimestamp = removalRequest.get(deviceId);
822 if (removalTimestamp != null &&
823 removalTimestamp.compareTo(timestampToCheck) >= 0) {
824 // removalRequest is more recent
825 return true;
826 }
827 return false;
828 }
829
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700830 /**
831 * Returns a Device, merging description given from multiple Providers.
832 *
833 * @param deviceId device identifier
834 * @param providerDescs Collection of Descriptions from multiple providers
835 * @return Device instance
836 */
837 private Device composeDevice(DeviceId deviceId,
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700838 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700839
Thomas Vachuska444eda62014-10-28 13:09:42 -0700840 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700841
842 ProviderId primary = pickPrimaryPID(providerDescs);
843
844 DeviceDescriptions desc = providerDescs.get(primary);
845
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700846 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700847 Type type = base.type();
848 String manufacturer = base.manufacturer();
849 String hwVersion = base.hwVersion();
850 String swVersion = base.swVersion();
851 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700852 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700853 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
854 annotations = merge(annotations, base.annotations());
855
856 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
857 if (e.getKey().equals(primary)) {
858 continue;
859 }
860 // TODO: should keep track of Description timestamp
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700861 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700862 // Currently assuming there will never be a key conflict between
863 // providers
864
865 // annotation merging. not so efficient, should revisit later
866 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
867 }
868
869 return new DefaultDevice(primary, deviceId , type, manufacturer,
alshabib7911a052014-10-16 17:49:37 -0700870 hwVersion, swVersion, serialNumber,
871 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700872 }
873
874 /**
875 * Returns a Port, merging description given from multiple Providers.
876 *
877 * @param device device the port is on
878 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700879 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700880 * @return Port instance
881 */
882 private Port composePort(Device device, PortNumber number,
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700883 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700884
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700885 ProviderId primary = pickPrimaryPID(descsMap);
886 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700887 // if no primary, assume not enabled
888 // TODO: revisit this default port enabled/disabled behavior
889 boolean isEnabled = false;
890 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
891
892 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
893 if (portDesc != null) {
894 isEnabled = portDesc.value().isEnabled();
895 annotations = merge(annotations, portDesc.value().annotations());
896 }
897
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700898 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700899 if (e.getKey().equals(primary)) {
900 continue;
901 }
902 // TODO: should keep track of Description timestamp
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700903 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700904 // Currently assuming there will never be a key conflict between
905 // providers
906
907 // annotation merging. not so efficient, should revisit later
908 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
909 if (otherPortDesc != null) {
910 annotations = merge(annotations, otherPortDesc.value().annotations());
911 }
912 }
913
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700914 return portDesc == null ?
915 new DefaultPort(device, number, false, annotations) :
916 new DefaultPort(device, number, isEnabled, portDesc.value().type(),
917 portDesc.value().portSpeed(), annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700918 }
919
920 /**
921 * @return primary ProviderID, or randomly chosen one if none exists
922 */
923 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700924 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700925 ProviderId fallBackPrimary = null;
926 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
927 if (!e.getKey().isAncillary()) {
928 return e.getKey();
929 } else if (fallBackPrimary == null) {
930 // pick randomly as a fallback in case there is no primary
931 fallBackPrimary = e.getKey();
932 }
933 }
934 return fallBackPrimary;
935 }
936
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700937 private DeviceDescriptions getPrimaryDescriptions(
938 Map<ProviderId, DeviceDescriptions> providerDescs) {
939 ProviderId pid = pickPrimaryPID(providerDescs);
940 return providerDescs.get(pid);
941 }
942
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700943 // TODO: should we be throwing exception?
944 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
945 ClusterMessage message = new ClusterMessage(
946 clusterService.getLocalNode().id(),
947 subject,
948 SERIALIZER.encode(event));
949 clusterCommunicator.unicast(message, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700950 }
951
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700952 // TODO: should we be throwing exception?
953 private void broadcastMessage(MessageSubject subject, Object event) throws IOException {
954 ClusterMessage message = new ClusterMessage(
955 clusterService.getLocalNode().id(),
956 subject,
957 SERIALIZER.encode(event));
958 clusterCommunicator.broadcast(message);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700959 }
Madan Jampani47c93732014-10-06 20:46:08 -0700960
961 private void notifyPeers(InternalDeviceEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700962 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -0700963 }
964
Madan Jampani25322532014-10-08 11:20:38 -0700965 private void notifyPeers(InternalDeviceOfflineEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700966 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -0700967 }
968
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700969 private void notifyPeers(InternalDeviceRemovedEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700970 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700971 }
972
Madan Jampani47c93732014-10-06 20:46:08 -0700973 private void notifyPeers(InternalPortEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700974 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -0700975 }
976
977 private void notifyPeers(InternalPortStatusEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700978 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
979 }
980
981 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
982 try {
983 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
984 } catch (IOException e) {
985 log.error("Failed to send" + event + " to " + recipient, e);
986 }
987 }
988
989 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
990 try {
991 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
992 } catch (IOException e) {
993 log.error("Failed to send" + event + " to " + recipient, e);
994 }
995 }
996
997 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
998 try {
999 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1000 } catch (IOException e) {
1001 log.error("Failed to send" + event + " to " + recipient, e);
1002 }
1003 }
1004
1005 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1006 try {
1007 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1008 } catch (IOException e) {
1009 log.error("Failed to send" + event + " to " + recipient, e);
1010 }
1011 }
1012
1013 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1014 try {
1015 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1016 } catch (IOException e) {
1017 log.error("Failed to send" + event + " to " + recipient, e);
1018 }
1019 }
1020
1021 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1022 final NodeId self = clusterService.getLocalNode().id();
1023
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001024 final int numDevices = deviceDescs.size();
1025 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1026 final int portsPerDevice = 8; // random factor to minimize reallocation
1027 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1028 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001029
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001030 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001031 provs : deviceDescs.entrySet()) {
1032
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001033 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001034 final DeviceId deviceId = provs.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001035 final Map<ProviderId, DeviceDescriptions> devDescs = provs.getValue();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001036 synchronized (devDescs) {
1037
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001038 // send device offline timestamp
1039 Timestamp lOffline = this.offline.get(deviceId);
1040 if (lOffline != null) {
1041 adOffline.put(deviceId, lOffline);
1042 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001043
1044 for (Entry<ProviderId, DeviceDescriptions>
1045 prov : devDescs.entrySet()) {
1046
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001047 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001048 final ProviderId provId = prov.getKey();
1049 final DeviceDescriptions descs = prov.getValue();
1050
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001051 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001052 descs.getDeviceDesc().timestamp());
1053
1054 for (Entry<PortNumber, Timestamped<PortDescription>>
1055 portDesc : descs.getPortDescs().entrySet()) {
1056
1057 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001058 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001059 portDesc.getValue().timestamp());
1060 }
1061 }
1062 }
1063 }
1064
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001065 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001066 }
1067
1068 /**
1069 * Responds to anti-entropy advertisement message.
1070 * <P>
1071 * Notify sender about out-dated information using regular replication message.
1072 * Send back advertisement to sender if not in sync.
1073 *
1074 * @param advertisement to respond to
1075 */
1076 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1077
1078 final NodeId sender = advertisement.sender();
1079
1080 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1081 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1082 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1083
1084 // Fragments to request
1085 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1086 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1087
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001088 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001089 final DeviceId deviceId = de.getKey();
1090 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1091
1092 synchronized (lDevice) {
1093 // latestTimestamp across provider
1094 // Note: can be null initially
1095 Timestamp localLatest = offline.get(deviceId);
1096
1097 // handle device Ads
1098 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1099 final ProviderId provId = prov.getKey();
1100 final DeviceDescriptions lDeviceDescs = prov.getValue();
1101
1102 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1103
1104
1105 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1106 Timestamp advDevTimestamp = devAds.get(devFragId);
1107
1108 if (advDevTimestamp == null || lProvDevice.isNewer(advDevTimestamp)) {
1109 // remote does not have it or outdated, suggest
1110 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1111 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1112 // local is outdated, request
1113 reqDevices.add(devFragId);
1114 }
1115
1116 // handle port Ads
1117 for (Entry<PortNumber, Timestamped<PortDescription>>
1118 pe : lDeviceDescs.getPortDescs().entrySet()) {
1119
1120 final PortNumber num = pe.getKey();
1121 final Timestamped<PortDescription> lPort = pe.getValue();
1122
1123 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1124
1125 Timestamp advPortTimestamp = portAds.get(portFragId);
Yuta HIGUCHIec76bfe2014-10-09 20:17:07 -07001126 if (advPortTimestamp == null || lPort.isNewer(advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001127 // remote does not have it or outdated, suggest
1128 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1129 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1130 // local is outdated, request
1131 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1132 reqPorts.add(portFragId);
1133 }
1134
1135 // remove port Ad already processed
1136 portAds.remove(portFragId);
1137 } // end local port loop
1138
1139 // remove device Ad already processed
1140 devAds.remove(devFragId);
1141
1142 // find latest and update
1143 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1144 if (localLatest == null ||
1145 providerLatest.compareTo(localLatest) > 0) {
1146 localLatest = providerLatest;
1147 }
1148 } // end local provider loop
1149
1150 // checking if remote timestamp is more recent.
1151 Timestamp rOffline = offlineAds.get(deviceId);
1152 if (rOffline != null &&
1153 rOffline.compareTo(localLatest) > 0) {
1154 // remote offline timestamp suggests that the
1155 // device is off-line
1156 markOfflineInternal(deviceId, rOffline);
1157 }
1158
1159 Timestamp lOffline = offline.get(deviceId);
1160 if (lOffline != null && rOffline == null) {
1161 // locally offline, but remote is online, suggest offline
1162 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1163 }
1164
1165 // remove device offline Ad already processed
1166 offlineAds.remove(deviceId);
1167 } // end local device loop
1168 } // device lock
1169
1170 // If there is any Ads left, request them
1171 log.trace("Ads left {}, {}", devAds, portAds);
1172 reqDevices.addAll(devAds.keySet());
1173 reqPorts.addAll(portAds.keySet());
1174
1175 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1176 log.trace("Nothing to request to remote peer {}", sender);
1177 return;
1178 }
1179
1180 log.info("Need to sync {} {}", reqDevices, reqPorts);
1181
1182 // 2-way Anti-Entropy for now
1183 try {
1184 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1185 } catch (IOException e) {
1186 log.error("Failed to send response advertisement to " + sender, e);
1187 }
1188
1189// Sketch of 3-way Anti-Entropy
1190// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1191// ClusterMessage message = new ClusterMessage(
1192// clusterService.getLocalNode().id(),
1193// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1194// SERIALIZER.encode(request));
1195//
1196// try {
1197// clusterCommunicator.unicast(message, advertisement.sender());
1198// } catch (IOException e) {
1199// log.error("Failed to send advertisement reply to "
1200// + advertisement.sender(), e);
1201// }
Madan Jampani47c93732014-10-06 20:46:08 -07001202 }
1203
Madan Jampani255a58b2014-10-09 12:08:20 -07001204 private void notifyDelegateIfNotNull(DeviceEvent event) {
1205 if (event != null) {
1206 notifyDelegate(event);
1207 }
1208 }
1209
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001210 private final class SendAdvertisementTask implements Runnable {
1211
1212 @Override
1213 public void run() {
1214 if (Thread.currentThread().isInterrupted()) {
1215 log.info("Interrupted, quitting");
1216 return;
1217 }
1218
1219 try {
1220 final NodeId self = clusterService.getLocalNode().id();
1221 Set<ControllerNode> nodes = clusterService.getNodes();
1222
1223 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1224 .transform(toNodeId())
1225 .toList();
1226
1227 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHI37083082014-10-13 10:38:38 -07001228 log.debug("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001229 return;
1230 }
1231
1232 NodeId peer;
1233 do {
1234 int idx = RandomUtils.nextInt(0, nodeIds.size());
1235 peer = nodeIds.get(idx);
1236 } while (peer.equals(self));
1237
1238 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1239
1240 if (Thread.currentThread().isInterrupted()) {
1241 log.info("Interrupted, quitting");
1242 return;
1243 }
1244
1245 try {
1246 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1247 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001248 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001249 return;
1250 }
1251 } catch (Exception e) {
1252 // catch all Exception to avoid Scheduled task being suppressed.
1253 log.error("Exception thrown while sending advertisement", e);
1254 }
1255 }
1256 }
1257
Madan Jampani47c93732014-10-06 20:46:08 -07001258 private class InternalDeviceEventListener implements ClusterMessageHandler {
1259 @Override
1260 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001261
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001262 log.debug("Received device update event from peer: {}", message.sender());
Madan Jampani53e44e62014-10-07 12:39:51 -07001263 InternalDeviceEvent event = (InternalDeviceEvent) SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001264
Madan Jampani47c93732014-10-06 20:46:08 -07001265 ProviderId providerId = event.providerId();
1266 DeviceId deviceId = event.deviceId();
1267 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001268
Madan Jampani255a58b2014-10-09 12:08:20 -07001269 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
Madan Jampani47c93732014-10-06 20:46:08 -07001270 }
1271 }
1272
Madan Jampani25322532014-10-08 11:20:38 -07001273 private class InternalDeviceOfflineEventListener implements ClusterMessageHandler {
1274 @Override
1275 public void handle(ClusterMessage message) {
1276
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001277 log.debug("Received device offline event from peer: {}", message.sender());
Madan Jampani25322532014-10-08 11:20:38 -07001278 InternalDeviceOfflineEvent event = (InternalDeviceOfflineEvent) SERIALIZER.decode(message.payload());
1279
1280 DeviceId deviceId = event.deviceId();
1281 Timestamp timestamp = event.timestamp();
1282
Madan Jampani255a58b2014-10-09 12:08:20 -07001283 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -07001284 }
1285 }
1286
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001287 private final class InternalRemoveRequestListener
1288 implements ClusterMessageHandler {
1289 @Override
1290 public void handle(ClusterMessage message) {
1291 log.debug("Received device remove request from peer: {}", message.sender());
1292 DeviceId did = SERIALIZER.decode(message.payload());
1293 removeDevice(did);
1294 }
1295 }
1296
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001297 private class InternalDeviceRemovedEventListener implements ClusterMessageHandler {
1298 @Override
1299 public void handle(ClusterMessage message) {
1300
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001301 log.debug("Received device removed event from peer: {}", message.sender());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001302 InternalDeviceRemovedEvent event = (InternalDeviceRemovedEvent) SERIALIZER.decode(message.payload());
1303
1304 DeviceId deviceId = event.deviceId();
1305 Timestamp timestamp = event.timestamp();
1306
Madan Jampani255a58b2014-10-09 12:08:20 -07001307 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001308 }
1309 }
1310
Madan Jampani47c93732014-10-06 20:46:08 -07001311 private class InternalPortEventListener implements ClusterMessageHandler {
1312 @Override
1313 public void handle(ClusterMessage message) {
1314
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001315 log.debug("Received port update event from peer: {}", message.sender());
Madan Jampani53e44e62014-10-07 12:39:51 -07001316 InternalPortEvent event = (InternalPortEvent) SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001317
1318 ProviderId providerId = event.providerId();
1319 DeviceId deviceId = event.deviceId();
1320 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1321
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001322 if (getDevice(deviceId) == null) {
1323 log.info("{} not found on this node yet, ignoring.", deviceId);
1324 // Note: dropped information will be recovered by anti-entropy
1325 return;
1326 }
1327
Madan Jampani255a58b2014-10-09 12:08:20 -07001328 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
Madan Jampani47c93732014-10-06 20:46:08 -07001329 }
1330 }
1331
1332 private class InternalPortStatusEventListener implements ClusterMessageHandler {
1333 @Override
1334 public void handle(ClusterMessage message) {
1335
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001336 log.debug("Received port status update event from peer: {}", message.sender());
Madan Jampani53e44e62014-10-07 12:39:51 -07001337 InternalPortStatusEvent event = (InternalPortStatusEvent) SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001338
1339 ProviderId providerId = event.providerId();
1340 DeviceId deviceId = event.deviceId();
1341 Timestamped<PortDescription> portDescription = event.portDescription();
1342
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001343 if (getDevice(deviceId) == null) {
1344 log.info("{} not found on this node yet, ignoring.", deviceId);
1345 // Note: dropped information will be recovered by anti-entropy
1346 return;
1347 }
1348
Madan Jampani255a58b2014-10-09 12:08:20 -07001349 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
Madan Jampani47c93732014-10-06 20:46:08 -07001350 }
1351 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001352
1353 private final class InternalDeviceAdvertisementListener
1354 implements ClusterMessageHandler {
1355
1356 @Override
1357 public void handle(ClusterMessage message) {
Yuta HIGUCHI9a0a1d12014-10-13 22:38:02 -07001358 log.debug("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001359 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
1360 handleAdvertisement(advertisement);
1361 }
1362 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001363}