blob: d11fa11c565efcabf8c451c48383567efaa13dc8 [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 HIGUCHI06586272014-11-25 14:27:03 -080092import static org.onlab.util.Tools.minPriority;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070093import static org.onlab.util.Tools.namedThreads;
94import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
95import static org.onlab.onos.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -080096import static org.onlab.onos.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070097
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -070098// TODO: give me a better name
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070099/**
100 * Manages inventory of infrastructure devices using gossip protocol to distribute
101 * information.
102 */
103@Component(immediate = true)
104@Service
105public class GossipDeviceStore
106 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
107 implements DeviceStore {
108
109 private final Logger log = getLogger(getClass());
110
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700111 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700112
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700113 // innerMap is used to lock a Device, thus instance should never be replaced.
114 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700115 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700116 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700117
118 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700119 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
120 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
121
122 // to be updated under Device lock
123 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
124 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700125
126 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700127 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700128
129 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700130 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700131
Madan Jampani47c93732014-10-06 20:46:08 -0700132 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
133 protected ClusterCommunicationService clusterCommunicator;
134
Madan Jampani53e44e62014-10-07 12:39:51 -0700135 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
136 protected ClusterService clusterService;
137
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700138 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
139 protected MastershipService mastershipService;
140
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800141 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
142 protected MastershipTermService termService;
143
144
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700145 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700146 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700147 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700148 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800149 .register(DistributedStoreSerializers.STORE_COMMON)
150 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
151 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
152 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700153 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800154 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
155 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700156 .register(DeviceAntiEntropyAdvertisement.class)
157 .register(DeviceFragmentId.class)
158 .register(PortFragmentId.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800159 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700160 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700161 };
162
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800163 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700164
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700165 @Activate
166 public void activate() {
Madan Jampani2206e012014-10-06 21:04:20 -0700167 clusterCommunicator.addSubscriber(
168 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener());
169 clusterCommunicator.addSubscriber(
Madan Jampani25322532014-10-08 11:20:38 -0700170 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, new InternalDeviceOfflineEventListener());
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800171 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ, new InternalRemoveRequestListener());
Madan Jampani25322532014-10-08 11:20:38 -0700172 clusterCommunicator.addSubscriber(
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700173 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener());
174 clusterCommunicator.addSubscriber(
Madan Jampani2206e012014-10-06 21:04:20 -0700175 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener());
176 clusterCommunicator.addSubscriber(
177 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700178 clusterCommunicator.addSubscriber(
179 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE, new InternalDeviceAdvertisementListener());
180
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800181 backgroundExecutor =
182 newSingleThreadScheduledExecutor(minPriority(namedThreads("device-bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700183
184 // TODO: Make these configurable
185 long initialDelaySec = 5;
186 long periodSec = 5;
187 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800188 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700189 initialDelaySec, periodSec, TimeUnit.SECONDS);
190
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700191 log.info("Started");
192 }
193
194 @Deactivate
195 public void deactivate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700196
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800197 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700198 try {
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800199 boolean timedout = backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700200 if (timedout) {
201 log.error("Timeout during executor shutdown");
202 }
203 } catch (InterruptedException e) {
204 log.error("Error during executor shutdown", e);
205 }
206
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700207 deviceDescs.clear();
208 devices.clear();
209 devicePorts.clear();
210 availableDevices.clear();
211 log.info("Stopped");
212 }
213
214 @Override
215 public int getDeviceCount() {
216 return devices.size();
217 }
218
219 @Override
220 public Iterable<Device> getDevices() {
221 return Collections.unmodifiableCollection(devices.values());
222 }
223
224 @Override
225 public Device getDevice(DeviceId deviceId) {
226 return devices.get(deviceId);
227 }
228
229 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700230 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
231 DeviceId deviceId,
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700232 DeviceDescription deviceDescription) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700233 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700234 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700235 final DeviceEvent event;
236 final Timestamped<DeviceDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800237 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
238 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700239 event = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800240 mergedDesc = device.get(providerId).getDeviceDesc();
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700241 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700242 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700243 log.info("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
244 providerId, deviceId);
245 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700246 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
Madan Jampani47c93732014-10-06 20:46:08 -0700247 } catch (IOException e) {
Madan Jampani25322532014-10-08 11:20:38 -0700248 log.error("Failed to notify peers of a device update topology event for providerId: "
Madan Jampani47c93732014-10-06 20:46:08 -0700249 + providerId + " and deviceId: " + deviceId, e);
250 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700251 }
252 return event;
253 }
254
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700255 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
256 DeviceId deviceId,
257 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700258
259 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800260 Map<ProviderId, DeviceDescriptions> device
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700261 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700262
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800263 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700264 // locking per device
265
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700266 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
267 log.debug("Ignoring outdated event: {}", deltaDesc);
268 return null;
269 }
270
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800271 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700272
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700273 final Device oldDevice = devices.get(deviceId);
274 final Device newDevice;
275
276 if (deltaDesc == descs.getDeviceDesc() ||
277 deltaDesc.isNewer(descs.getDeviceDesc())) {
278 // on new device or valid update
279 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800280 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700281 } else {
282 // outdated event, ignored.
283 return null;
284 }
285 if (oldDevice == null) {
286 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700287 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700288 } else {
289 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700290 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700291 }
292 }
293 }
294
295 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700296 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700297 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700298 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700299
300 // update composed device cache
301 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
302 verify(oldDevice == null,
303 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
304 providerId, oldDevice, newDevice);
305
306 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700307 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700308 }
309
310 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
311 }
312
313 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700314 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700315 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700316 Device oldDevice,
317 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700318 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700319 boolean propertiesChanged =
320 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
321 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion());
322 boolean annotationsChanged =
323 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700324
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700325 // Primary providers can respond to all changes, but ancillary ones
326 // should respond only to annotation changes.
327 if ((providerId.isAncillary() && annotationsChanged) ||
328 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700329 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
330 if (!replaced) {
331 verify(replaced,
332 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
333 providerId, oldDevice, devices.get(newDevice.id())
334 , newDevice);
335 }
336 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700337 markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700338 }
339 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
340 }
341
342 // Otherwise merely attempt to change availability if primary provider
343 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700344 boolean added = markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700345 return !added ? null :
346 new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null);
347 }
348 return null;
349 }
350
351 @Override
352 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700353 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700354 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700355 if (event != null) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700356 log.info("Notifying peers of a device offline topology event for deviceId: {} {}",
357 deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700358 try {
359 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
360 } catch (IOException e) {
361 log.error("Failed to notify peers of a device offline topology event for deviceId: {}",
362 deviceId);
363 }
364 }
365 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700366 }
367
368 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
369
370 Map<ProviderId, DeviceDescriptions> providerDescs
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700371 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700372
373 // locking device
374 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700375
376 // accept off-line if given timestamp is newer than
377 // the latest Timestamp from Primary provider
378 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
379 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
380 if (timestamp.compareTo(lastTimestamp) <= 0) {
381 // outdated event ignore
382 return null;
383 }
384
385 offline.put(deviceId, timestamp);
386
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700387 Device device = devices.get(deviceId);
388 if (device == null) {
389 return null;
390 }
391 boolean removed = availableDevices.remove(deviceId);
392 if (removed) {
393 // TODO: broadcast ... DOWN only?
394 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700395 }
396 return null;
397 }
398 }
399
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700400 /**
401 * Marks the device as available if the given timestamp is not outdated,
402 * compared to the time the device has been marked offline.
403 *
404 * @param deviceId identifier of the device
405 * @param timestamp of the event triggering this change.
406 * @return true if availability change request was accepted and changed the state
407 */
408 // Guarded by deviceDescs value (=Device lock)
409 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
410 // accept on-line if given timestamp is newer than
411 // the latest offline request Timestamp
412 Timestamp offlineTimestamp = offline.get(deviceId);
413 if (offlineTimestamp == null ||
414 offlineTimestamp.compareTo(timestamp) < 0) {
415
416 offline.remove(deviceId);
417 return availableDevices.add(deviceId);
418 }
419 return false;
420 }
421
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700422 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700423 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
424 DeviceId deviceId,
425 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700426
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700427 final Timestamp newTimestamp;
428 try {
429 newTimestamp = deviceClockService.getTimestamp(deviceId);
430 } catch (IllegalStateException e) {
431 log.info("Timestamp was not available for device {}", deviceId);
432 log.debug(" discarding {}", portDescriptions);
433 // Failed to generate timestamp.
434
435 // Possible situation:
436 // Device connected and became master for short period of time,
437 // but lost mastership before this instance had the chance to
438 // retrieve term information.
439
440 // Information dropped here is expected to be recoverable by
441 // device probing after mastership change
442
443 return Collections.emptyList();
444 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800445 log.debug("timestamp for {} {}", deviceId, newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700446
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700447 final Timestamped<List<PortDescription>> timestampedInput
448 = new Timestamped<>(portDescriptions, newTimestamp);
449 final List<DeviceEvent> events;
450 final Timestamped<List<PortDescription>> merged;
451
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800452 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
453 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700454 events = updatePortsInternal(providerId, deviceId, timestampedInput);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800455 final DeviceDescriptions descs = device.get(providerId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700456 List<PortDescription> mergedList =
457 FluentIterable.from(portDescriptions)
458 .transform(new Function<PortDescription, PortDescription>() {
459 @Override
460 public PortDescription apply(PortDescription input) {
461 // lookup merged port description
462 return descs.getPortDesc(input.portNumber()).value();
463 }
464 }).toList();
465 merged = new Timestamped<List<PortDescription>>(mergedList, newTimestamp);
466 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700467 if (!events.isEmpty()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800468 log.info("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Madan Jampani47c93732014-10-06 20:46:08 -0700469 providerId, deviceId);
470 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700471 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
Madan Jampani47c93732014-10-06 20:46:08 -0700472 } catch (IOException e) {
473 log.error("Failed to notify peers of a port update topology event or providerId: "
474 + providerId + " and deviceId: " + deviceId, e);
475 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700476 }
477 return events;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700478 }
479
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700480 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
481 DeviceId deviceId,
482 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700483
484 Device device = devices.get(deviceId);
485 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
486
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700487 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700488 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
489
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700490 List<DeviceEvent> events = new ArrayList<>();
491 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700492
493 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
494 log.debug("Ignoring outdated events: {}", portDescriptions);
495 return null;
496 }
497
498 DeviceDescriptions descs = descsMap.get(providerId);
499 // every provider must provide DeviceDescription.
500 checkArgument(descs != null,
501 "Device description for Device ID %s from Provider %s was not found",
502 deviceId, providerId);
503
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700504 Map<PortNumber, Port> ports = getPortMap(deviceId);
505
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700506 final Timestamp newTimestamp = portDescriptions.timestamp();
507
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700508 // Add new ports
509 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700510 for (PortDescription portDescription : portDescriptions.value()) {
511 final PortNumber number = portDescription.portNumber();
512 processed.add(number);
513
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700514 final Port oldPort = ports.get(number);
515 final Port newPort;
516
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700517
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700518 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
519 if (existingPortDesc == null ||
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700520 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700521 // on new port or valid update
522 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700523 descs.putPortDesc(new Timestamped<>(portDescription,
524 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700525 newPort = composePort(device, number, descsMap);
526 } else {
527 // outdated event, ignored.
528 continue;
529 }
530
531 events.add(oldPort == null ?
532 createPort(device, newPort, ports) :
533 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700534 }
535
536 events.addAll(pruneOldPorts(device, ports, processed));
537 }
538 return FluentIterable.from(events).filter(notNull()).toList();
539 }
540
541 // Creates a new port based on the port description adds it to the map and
542 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700543 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700544 private DeviceEvent createPort(Device device, Port newPort,
545 Map<PortNumber, Port> ports) {
546 ports.put(newPort.number(), newPort);
547 return new DeviceEvent(PORT_ADDED, device, newPort);
548 }
549
550 // Checks if the specified port requires update and if so, it replaces the
551 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700552 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700553 private DeviceEvent updatePort(Device device, Port oldPort,
554 Port newPort,
555 Map<PortNumber, Port> ports) {
556 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700557 oldPort.type() != newPort.type() ||
558 oldPort.portSpeed() != newPort.portSpeed() ||
559 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700560 ports.put(oldPort.number(), newPort);
561 return new DeviceEvent(PORT_UPDATED, device, newPort);
562 }
563 return null;
564 }
565
566 // Prunes the specified list of ports based on which ports are in the
567 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700568 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700569 private List<DeviceEvent> pruneOldPorts(Device device,
570 Map<PortNumber, Port> ports,
571 Set<PortNumber> processed) {
572 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700573 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700574 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700575 Entry<PortNumber, Port> e = iterator.next();
576 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700577 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700578 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700579 iterator.remove();
580 }
581 }
582 return events;
583 }
584
585 // Gets the map of ports for the specified device; if one does not already
586 // exist, it creates and registers a new one.
587 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
588 return createIfAbsentUnchecked(devicePorts, deviceId,
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700589 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
590 }
591
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700592 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700593 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700594 Map<ProviderId, DeviceDescriptions> r;
595 r = deviceDescs.get(deviceId);
596 if (r == null) {
597 r = new HashMap<ProviderId, DeviceDescriptions>();
598 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
599 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
600 if (concurrentlyAdded != null) {
601 r = concurrentlyAdded;
602 }
603 }
604 return r;
605 }
606
607 // Guarded by deviceDescs value (=Device lock)
608 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
609 Map<ProviderId, DeviceDescriptions> device,
610 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
611
612 synchronized (device) {
613 DeviceDescriptions r = device.get(providerId);
614 if (r == null) {
615 r = new DeviceDescriptions(deltaDesc);
616 device.put(providerId, r);
617 }
618 return r;
619 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700620 }
621
622 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700623 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
624 DeviceId deviceId,
625 PortDescription portDescription) {
626
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700627 final Timestamp newTimestamp;
628 try {
629 newTimestamp = deviceClockService.getTimestamp(deviceId);
630 } catch (IllegalStateException e) {
631 log.info("Timestamp was not available for device {}", deviceId);
632 log.debug(" discarding {}", portDescription);
633 // Failed to generate timestamp. Ignoring.
634 // See updatePorts comment
635 return null;
636 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700637 final Timestamped<PortDescription> deltaDesc
638 = new Timestamped<>(portDescription, newTimestamp);
639 final DeviceEvent event;
640 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800641 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
642 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700643 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800644 mergedDesc = device.get(providerId)
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700645 .getPortDesc(portDescription.portNumber());
646 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700647 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700648 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
649 providerId, deviceId);
650 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700651 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Madan Jampani47c93732014-10-06 20:46:08 -0700652 } catch (IOException e) {
653 log.error("Failed to notify peers of a port status update topology event or providerId: "
654 + providerId + " and deviceId: " + deviceId, e);
655 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700656 }
657 return event;
658 }
659
660 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
661 Timestamped<PortDescription> deltaDesc) {
662
663 Device device = devices.get(deviceId);
664 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
665
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700666 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700667 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
668
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700669 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700670
671 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
672 log.debug("Ignoring outdated event: {}", deltaDesc);
673 return null;
674 }
675
676 DeviceDescriptions descs = descsMap.get(providerId);
677 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700678 verify(descs != null,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700679 "Device description for Device ID %s from Provider %s was not found",
680 deviceId, providerId);
681
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700682 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
683 final PortNumber number = deltaDesc.value().portNumber();
684 final Port oldPort = ports.get(number);
685 final Port newPort;
686
687 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
688 if (existingPortDesc == null ||
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700689 deltaDesc.isNewer(existingPortDesc)) {
690 // on new port or valid update
691 // update description
692 descs.putPortDesc(deltaDesc);
693 newPort = composePort(device, number, descsMap);
694 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700695 // same or outdated event, ignored.
696 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700697 return null;
698 }
699
700 if (oldPort == null) {
701 return createPort(device, newPort, ports);
702 } else {
703 return updatePort(device, oldPort, newPort, ports);
704 }
705 }
706 }
707
708 @Override
709 public List<Port> getPorts(DeviceId deviceId) {
710 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
711 if (ports == null) {
712 return Collections.emptyList();
713 }
714 return ImmutableList.copyOf(ports.values());
715 }
716
717 @Override
718 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
719 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
720 return ports == null ? null : ports.get(portNumber);
721 }
722
723 @Override
724 public boolean isAvailable(DeviceId deviceId) {
725 return availableDevices.contains(deviceId);
726 }
727
728 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700729 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800730 final NodeId myId = clusterService.getLocalNode().id();
731 NodeId master = mastershipService.getMasterFor(deviceId);
732
733 // if there exist a master, forward
734 // if there is no master, try to become one and process
735
736 boolean relinquishAtEnd = false;
737 if (master == null) {
738 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
739 if (myRole != MastershipRole.NONE) {
740 relinquishAtEnd = true;
741 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800742 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800743 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800744 MastershipTerm term = termService.getMastershipTerm(deviceId);
745 if (myId.equals(term.master())) {
746 master = myId;
747 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700748 }
749
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800750 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800751 log.debug("{} has control of {}, forwarding remove request",
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800752 master, deviceId);
753
754 ClusterMessage message = new ClusterMessage(
755 myId,
756 DEVICE_REMOVE_REQ,
757 SERIALIZER.encode(deviceId));
758
759 try {
760 clusterCommunicator.unicast(message, master);
761 } catch (IOException e) {
762 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
763 }
764
765 // event will be triggered after master processes it.
766 return null;
767 }
768
769 // I have control..
770
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700771 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700772 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700773 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800774 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700775 deviceId);
776 try {
777 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
778 } catch (IOException e) {
779 log.error("Failed to notify peers of a device removed topology event for deviceId: {}",
780 deviceId);
781 }
782 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800783 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800784 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800785 mastershipService.relinquishMastership(deviceId);
786 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700787 return event;
788 }
789
790 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
791 Timestamp timestamp) {
792
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700793 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700794 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700795 // accept removal request if given timestamp is newer than
796 // the latest Timestamp from Primary provider
797 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
798 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
799 if (timestamp.compareTo(lastTimestamp) <= 0) {
800 // outdated event ignore
801 return null;
802 }
803 removalRequest.put(deviceId, timestamp);
804
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700805 Device device = devices.remove(deviceId);
806 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700807 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
808 if (ports != null) {
809 ports.clear();
810 }
811 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700812 descs.clear();
813 return device == null ? null :
814 new DeviceEvent(DEVICE_REMOVED, device, null);
815 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700816 }
817
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700818 /**
819 * Checks if given timestamp is superseded by removal request
820 * with more recent timestamp.
821 *
822 * @param deviceId identifier of a device
823 * @param timestampToCheck timestamp of an event to check
824 * @return true if device is already removed
825 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700826 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
827 Timestamp removalTimestamp = removalRequest.get(deviceId);
828 if (removalTimestamp != null &&
829 removalTimestamp.compareTo(timestampToCheck) >= 0) {
830 // removalRequest is more recent
831 return true;
832 }
833 return false;
834 }
835
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700836 /**
837 * Returns a Device, merging description given from multiple Providers.
838 *
839 * @param deviceId device identifier
840 * @param providerDescs Collection of Descriptions from multiple providers
841 * @return Device instance
842 */
843 private Device composeDevice(DeviceId deviceId,
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700844 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700845
Thomas Vachuska444eda62014-10-28 13:09:42 -0700846 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700847
848 ProviderId primary = pickPrimaryPID(providerDescs);
849
850 DeviceDescriptions desc = providerDescs.get(primary);
851
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700852 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700853 Type type = base.type();
854 String manufacturer = base.manufacturer();
855 String hwVersion = base.hwVersion();
856 String swVersion = base.swVersion();
857 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700858 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700859 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
860 annotations = merge(annotations, base.annotations());
861
862 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
863 if (e.getKey().equals(primary)) {
864 continue;
865 }
866 // TODO: should keep track of Description timestamp
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700867 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700868 // Currently assuming there will never be a key conflict between
869 // providers
870
871 // annotation merging. not so efficient, should revisit later
872 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
873 }
874
875 return new DefaultDevice(primary, deviceId , type, manufacturer,
alshabib7911a052014-10-16 17:49:37 -0700876 hwVersion, swVersion, serialNumber,
877 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700878 }
879
880 /**
881 * Returns a Port, merging description given from multiple Providers.
882 *
883 * @param device device the port is on
884 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700885 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700886 * @return Port instance
887 */
888 private Port composePort(Device device, PortNumber number,
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700889 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700890
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700891 ProviderId primary = pickPrimaryPID(descsMap);
892 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700893 // if no primary, assume not enabled
894 // TODO: revisit this default port enabled/disabled behavior
895 boolean isEnabled = false;
896 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
897
898 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
899 if (portDesc != null) {
900 isEnabled = portDesc.value().isEnabled();
901 annotations = merge(annotations, portDesc.value().annotations());
902 }
903
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700904 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700905 if (e.getKey().equals(primary)) {
906 continue;
907 }
908 // TODO: should keep track of Description timestamp
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700909 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700910 // Currently assuming there will never be a key conflict between
911 // providers
912
913 // annotation merging. not so efficient, should revisit later
914 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
915 if (otherPortDesc != null) {
916 annotations = merge(annotations, otherPortDesc.value().annotations());
917 }
918 }
919
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700920 return portDesc == null ?
921 new DefaultPort(device, number, false, annotations) :
922 new DefaultPort(device, number, isEnabled, portDesc.value().type(),
923 portDesc.value().portSpeed(), annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700924 }
925
926 /**
927 * @return primary ProviderID, or randomly chosen one if none exists
928 */
929 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700930 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700931 ProviderId fallBackPrimary = null;
932 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
933 if (!e.getKey().isAncillary()) {
934 return e.getKey();
935 } else if (fallBackPrimary == null) {
936 // pick randomly as a fallback in case there is no primary
937 fallBackPrimary = e.getKey();
938 }
939 }
940 return fallBackPrimary;
941 }
942
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700943 private DeviceDescriptions getPrimaryDescriptions(
944 Map<ProviderId, DeviceDescriptions> providerDescs) {
945 ProviderId pid = pickPrimaryPID(providerDescs);
946 return providerDescs.get(pid);
947 }
948
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700949 // TODO: should we be throwing exception?
950 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
951 ClusterMessage message = new ClusterMessage(
952 clusterService.getLocalNode().id(),
953 subject,
954 SERIALIZER.encode(event));
955 clusterCommunicator.unicast(message, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700956 }
957
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700958 // TODO: should we be throwing exception?
959 private void broadcastMessage(MessageSubject subject, Object event) throws IOException {
960 ClusterMessage message = new ClusterMessage(
961 clusterService.getLocalNode().id(),
962 subject,
963 SERIALIZER.encode(event));
964 clusterCommunicator.broadcast(message);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700965 }
Madan Jampani47c93732014-10-06 20:46:08 -0700966
967 private void notifyPeers(InternalDeviceEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700968 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -0700969 }
970
Madan Jampani25322532014-10-08 11:20:38 -0700971 private void notifyPeers(InternalDeviceOfflineEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700972 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -0700973 }
974
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700975 private void notifyPeers(InternalDeviceRemovedEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700976 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700977 }
978
Madan Jampani47c93732014-10-06 20:46:08 -0700979 private void notifyPeers(InternalPortEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700980 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -0700981 }
982
983 private void notifyPeers(InternalPortStatusEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700984 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
985 }
986
987 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
988 try {
989 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
990 } catch (IOException e) {
991 log.error("Failed to send" + event + " to " + recipient, e);
992 }
993 }
994
995 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
996 try {
997 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
998 } catch (IOException e) {
999 log.error("Failed to send" + event + " to " + recipient, e);
1000 }
1001 }
1002
1003 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1004 try {
1005 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1006 } catch (IOException e) {
1007 log.error("Failed to send" + event + " to " + recipient, e);
1008 }
1009 }
1010
1011 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1012 try {
1013 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1014 } catch (IOException e) {
1015 log.error("Failed to send" + event + " to " + recipient, e);
1016 }
1017 }
1018
1019 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1020 try {
1021 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1022 } catch (IOException e) {
1023 log.error("Failed to send" + event + " to " + recipient, e);
1024 }
1025 }
1026
1027 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1028 final NodeId self = clusterService.getLocalNode().id();
1029
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001030 final int numDevices = deviceDescs.size();
1031 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1032 final int portsPerDevice = 8; // random factor to minimize reallocation
1033 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1034 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001035
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001036 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001037
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001038 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001039 synchronized (devDescs) {
1040
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001041 // send device offline timestamp
1042 Timestamp lOffline = this.offline.get(deviceId);
1043 if (lOffline != null) {
1044 adOffline.put(deviceId, lOffline);
1045 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001046
1047 for (Entry<ProviderId, DeviceDescriptions>
1048 prov : devDescs.entrySet()) {
1049
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001050 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001051 final ProviderId provId = prov.getKey();
1052 final DeviceDescriptions descs = prov.getValue();
1053
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001054 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001055 descs.getDeviceDesc().timestamp());
1056
1057 for (Entry<PortNumber, Timestamped<PortDescription>>
1058 portDesc : descs.getPortDescs().entrySet()) {
1059
1060 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001061 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001062 portDesc.getValue().timestamp());
1063 }
1064 }
1065 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001066 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001067
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001068 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001069 }
1070
1071 /**
1072 * Responds to anti-entropy advertisement message.
1073 * <P>
1074 * Notify sender about out-dated information using regular replication message.
1075 * Send back advertisement to sender if not in sync.
1076 *
1077 * @param advertisement to respond to
1078 */
1079 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1080
1081 final NodeId sender = advertisement.sender();
1082
1083 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1084 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1085 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1086
1087 // Fragments to request
1088 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1089 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1090
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001091 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001092 final DeviceId deviceId = de.getKey();
1093 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1094
1095 synchronized (lDevice) {
1096 // latestTimestamp across provider
1097 // Note: can be null initially
1098 Timestamp localLatest = offline.get(deviceId);
1099
1100 // handle device Ads
1101 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1102 final ProviderId provId = prov.getKey();
1103 final DeviceDescriptions lDeviceDescs = prov.getValue();
1104
1105 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1106
1107
1108 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1109 Timestamp advDevTimestamp = devAds.get(devFragId);
1110
1111 if (advDevTimestamp == null || lProvDevice.isNewer(advDevTimestamp)) {
1112 // remote does not have it or outdated, suggest
1113 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1114 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1115 // local is outdated, request
1116 reqDevices.add(devFragId);
1117 }
1118
1119 // handle port Ads
1120 for (Entry<PortNumber, Timestamped<PortDescription>>
1121 pe : lDeviceDescs.getPortDescs().entrySet()) {
1122
1123 final PortNumber num = pe.getKey();
1124 final Timestamped<PortDescription> lPort = pe.getValue();
1125
1126 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1127
1128 Timestamp advPortTimestamp = portAds.get(portFragId);
Yuta HIGUCHIec76bfe2014-10-09 20:17:07 -07001129 if (advPortTimestamp == null || lPort.isNewer(advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001130 // remote does not have it or outdated, suggest
1131 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1132 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1133 // local is outdated, request
1134 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1135 reqPorts.add(portFragId);
1136 }
1137
1138 // remove port Ad already processed
1139 portAds.remove(portFragId);
1140 } // end local port loop
1141
1142 // remove device Ad already processed
1143 devAds.remove(devFragId);
1144
1145 // find latest and update
1146 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1147 if (localLatest == null ||
1148 providerLatest.compareTo(localLatest) > 0) {
1149 localLatest = providerLatest;
1150 }
1151 } // end local provider loop
1152
1153 // checking if remote timestamp is more recent.
1154 Timestamp rOffline = offlineAds.get(deviceId);
1155 if (rOffline != null &&
1156 rOffline.compareTo(localLatest) > 0) {
1157 // remote offline timestamp suggests that the
1158 // device is off-line
1159 markOfflineInternal(deviceId, rOffline);
1160 }
1161
1162 Timestamp lOffline = offline.get(deviceId);
1163 if (lOffline != null && rOffline == null) {
1164 // locally offline, but remote is online, suggest offline
1165 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1166 }
1167
1168 // remove device offline Ad already processed
1169 offlineAds.remove(deviceId);
1170 } // end local device loop
1171 } // device lock
1172
1173 // If there is any Ads left, request them
1174 log.trace("Ads left {}, {}", devAds, portAds);
1175 reqDevices.addAll(devAds.keySet());
1176 reqPorts.addAll(portAds.keySet());
1177
1178 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1179 log.trace("Nothing to request to remote peer {}", sender);
1180 return;
1181 }
1182
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001183 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001184
1185 // 2-way Anti-Entropy for now
1186 try {
1187 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1188 } catch (IOException e) {
1189 log.error("Failed to send response advertisement to " + sender, e);
1190 }
1191
1192// Sketch of 3-way Anti-Entropy
1193// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1194// ClusterMessage message = new ClusterMessage(
1195// clusterService.getLocalNode().id(),
1196// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1197// SERIALIZER.encode(request));
1198//
1199// try {
1200// clusterCommunicator.unicast(message, advertisement.sender());
1201// } catch (IOException e) {
1202// log.error("Failed to send advertisement reply to "
1203// + advertisement.sender(), e);
1204// }
Madan Jampani47c93732014-10-06 20:46:08 -07001205 }
1206
Madan Jampani255a58b2014-10-09 12:08:20 -07001207 private void notifyDelegateIfNotNull(DeviceEvent event) {
1208 if (event != null) {
1209 notifyDelegate(event);
1210 }
1211 }
1212
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001213 private final class SendAdvertisementTask implements Runnable {
1214
1215 @Override
1216 public void run() {
1217 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001218 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001219 return;
1220 }
1221
1222 try {
1223 final NodeId self = clusterService.getLocalNode().id();
1224 Set<ControllerNode> nodes = clusterService.getNodes();
1225
1226 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1227 .transform(toNodeId())
1228 .toList();
1229
1230 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001231 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001232 return;
1233 }
1234
1235 NodeId peer;
1236 do {
1237 int idx = RandomUtils.nextInt(0, nodeIds.size());
1238 peer = nodeIds.get(idx);
1239 } while (peer.equals(self));
1240
1241 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1242
1243 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001244 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001245 return;
1246 }
1247
1248 try {
1249 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1250 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001251 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001252 return;
1253 }
1254 } catch (Exception e) {
1255 // catch all Exception to avoid Scheduled task being suppressed.
1256 log.error("Exception thrown while sending advertisement", e);
1257 }
1258 }
1259 }
1260
Madan Jampani47c93732014-10-06 20:46:08 -07001261 private class InternalDeviceEventListener implements ClusterMessageHandler {
1262 @Override
1263 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001264
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001265 log.debug("Received device update event from peer: {}", message.sender());
Madan Jampani53e44e62014-10-07 12:39:51 -07001266 InternalDeviceEvent event = (InternalDeviceEvent) SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001267
Madan Jampani47c93732014-10-06 20:46:08 -07001268 ProviderId providerId = event.providerId();
1269 DeviceId deviceId = event.deviceId();
1270 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001271
Madan Jampani255a58b2014-10-09 12:08:20 -07001272 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
Madan Jampani47c93732014-10-06 20:46:08 -07001273 }
1274 }
1275
Madan Jampani25322532014-10-08 11:20:38 -07001276 private class InternalDeviceOfflineEventListener implements ClusterMessageHandler {
1277 @Override
1278 public void handle(ClusterMessage message) {
1279
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001280 log.debug("Received device offline event from peer: {}", message.sender());
Madan Jampani25322532014-10-08 11:20:38 -07001281 InternalDeviceOfflineEvent event = (InternalDeviceOfflineEvent) SERIALIZER.decode(message.payload());
1282
1283 DeviceId deviceId = event.deviceId();
1284 Timestamp timestamp = event.timestamp();
1285
Madan Jampani255a58b2014-10-09 12:08:20 -07001286 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -07001287 }
1288 }
1289
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001290 private final class InternalRemoveRequestListener
1291 implements ClusterMessageHandler {
1292 @Override
1293 public void handle(ClusterMessage message) {
1294 log.debug("Received device remove request from peer: {}", message.sender());
1295 DeviceId did = SERIALIZER.decode(message.payload());
1296 removeDevice(did);
1297 }
1298 }
1299
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001300 private class InternalDeviceRemovedEventListener implements ClusterMessageHandler {
1301 @Override
1302 public void handle(ClusterMessage message) {
1303
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001304 log.debug("Received device removed event from peer: {}", message.sender());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001305 InternalDeviceRemovedEvent event = (InternalDeviceRemovedEvent) SERIALIZER.decode(message.payload());
1306
1307 DeviceId deviceId = event.deviceId();
1308 Timestamp timestamp = event.timestamp();
1309
Madan Jampani255a58b2014-10-09 12:08:20 -07001310 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001311 }
1312 }
1313
Madan Jampani47c93732014-10-06 20:46:08 -07001314 private class InternalPortEventListener implements ClusterMessageHandler {
1315 @Override
1316 public void handle(ClusterMessage message) {
1317
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001318 log.debug("Received port update event from peer: {}", message.sender());
Madan Jampani53e44e62014-10-07 12:39:51 -07001319 InternalPortEvent event = (InternalPortEvent) SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001320
1321 ProviderId providerId = event.providerId();
1322 DeviceId deviceId = event.deviceId();
1323 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1324
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001325 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001326 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001327 // Note: dropped information will be recovered by anti-entropy
1328 return;
1329 }
1330
Madan Jampani255a58b2014-10-09 12:08:20 -07001331 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
Madan Jampani47c93732014-10-06 20:46:08 -07001332 }
1333 }
1334
1335 private class InternalPortStatusEventListener implements ClusterMessageHandler {
1336 @Override
1337 public void handle(ClusterMessage message) {
1338
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001339 log.debug("Received port status update event from peer: {}", message.sender());
Madan Jampani53e44e62014-10-07 12:39:51 -07001340 InternalPortStatusEvent event = (InternalPortStatusEvent) SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001341
1342 ProviderId providerId = event.providerId();
1343 DeviceId deviceId = event.deviceId();
1344 Timestamped<PortDescription> portDescription = event.portDescription();
1345
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001346 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001347 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001348 // Note: dropped information will be recovered by anti-entropy
1349 return;
1350 }
1351
Madan Jampani255a58b2014-10-09 12:08:20 -07001352 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
Madan Jampani47c93732014-10-06 20:46:08 -07001353 }
1354 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001355
1356 private final class InternalDeviceAdvertisementListener
1357 implements ClusterMessageHandler {
1358
1359 @Override
1360 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001361 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001362 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Yuta HIGUCHI06586272014-11-25 14:27:03 -08001363 backgroundExecutor.submit(new Runnable() {
1364
1365 @Override
1366 public void run() {
1367 try {
1368 handleAdvertisement(advertisement);
1369 } catch (Exception e) {
1370 log.warn("Exception thrown handling Device advertisements.", e);
1371 }
1372 }
1373 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001374 }
1375 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001376}