blob: 03c0cb6495ab85077f699fe2efc75ca1d18e23d4 [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 HIGUCHIf1f2ac02014-11-26 14:02:22 -080019import com.google.common.base.Predicate;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070020import com.google.common.collect.FluentIterable;
21import com.google.common.collect.ImmutableList;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -070022import com.google.common.collect.Maps;
23import com.google.common.collect.Sets;
Madan Jampani47c93732014-10-06 20:46:08 -070024
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070025import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070026import org.apache.felix.scr.annotations.Activate;
27import org.apache.felix.scr.annotations.Component;
28import org.apache.felix.scr.annotations.Deactivate;
29import org.apache.felix.scr.annotations.Reference;
30import org.apache.felix.scr.annotations.ReferenceCardinality;
31import org.apache.felix.scr.annotations.Service;
Madan Jampani53e44e62014-10-07 12:39:51 -070032import org.onlab.onos.cluster.ClusterService;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070033import org.onlab.onos.cluster.ControllerNode;
34import org.onlab.onos.cluster.NodeId;
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -070035import org.onlab.onos.mastership.MastershipService;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -080036import org.onlab.onos.mastership.MastershipTerm;
37import org.onlab.onos.mastership.MastershipTermService;
Yuta HIGUCHI39ede6a2014-10-03 15:23:33 -070038import org.onlab.onos.net.AnnotationsUtil;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070039import org.onlab.onos.net.DefaultAnnotations;
40import org.onlab.onos.net.DefaultDevice;
41import org.onlab.onos.net.DefaultPort;
42import org.onlab.onos.net.Device;
43import org.onlab.onos.net.Device.Type;
44import org.onlab.onos.net.DeviceId;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -080045import org.onlab.onos.net.MastershipRole;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070046import org.onlab.onos.net.Port;
47import org.onlab.onos.net.PortNumber;
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -070048import org.onlab.onos.net.device.DeviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070049import org.onlab.onos.net.device.DeviceDescription;
50import org.onlab.onos.net.device.DeviceEvent;
51import org.onlab.onos.net.device.DeviceStore;
52import org.onlab.onos.net.device.DeviceStoreDelegate;
53import org.onlab.onos.net.device.PortDescription;
54import org.onlab.onos.net.provider.ProviderId;
55import org.onlab.onos.store.AbstractStore;
Yuta HIGUCHId40483d2014-10-09 15:20:30 -070056import org.onlab.onos.store.Timestamp;
Madan Jampani47c93732014-10-06 20:46:08 -070057import org.onlab.onos.store.cluster.messaging.ClusterCommunicationService;
58import org.onlab.onos.store.cluster.messaging.ClusterMessage;
59import org.onlab.onos.store.cluster.messaging.ClusterMessageHandler;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070060import org.onlab.onos.store.cluster.messaging.MessageSubject;
Yuta HIGUCHIeecee552014-10-16 14:09:01 -070061import org.onlab.onos.store.impl.Timestamped;
Madan Jampani53e44e62014-10-07 12:39:51 -070062import org.onlab.onos.store.serializers.KryoSerializer;
Yuta HIGUCHI60a190b2014-11-07 16:24:47 -080063import org.onlab.onos.store.serializers.impl.DistributedStoreSerializers;
alshabib7911a052014-10-16 17:49:37 -070064import org.onlab.packet.ChassisId;
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -070065import org.onlab.util.KryoNamespace;
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -070066import org.onlab.util.NewConcurrentHashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070067import org.slf4j.Logger;
68
Madan Jampani47c93732014-10-06 20:46:08 -070069import java.io.IOException;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070070import java.util.ArrayList;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070071import java.util.Collection;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070072import java.util.Collections;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070073import java.util.HashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070074import java.util.HashSet;
75import java.util.Iterator;
76import java.util.List;
77import java.util.Map;
78import java.util.Map.Entry;
79import java.util.Objects;
80import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070081import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080082import java.util.concurrent.ExecutorService;
83import java.util.concurrent.Executors;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070084import java.util.concurrent.ScheduledExecutorService;
85import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070086
87import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070088import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHIdc7374c2014-10-10 11:11:09 -070089import static org.onlab.onos.cluster.ControllerNodeToNodeId.toNodeId;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070090import static org.onlab.onos.net.device.DeviceEvent.Type.*;
91import static org.slf4j.LoggerFactory.getLogger;
92import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
93import static org.onlab.onos.net.DefaultAnnotations.merge;
94import static com.google.common.base.Verify.verify;
Yuta HIGUCHI06586272014-11-25 14:27:03 -080095import static org.onlab.util.Tools.minPriority;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070096import static org.onlab.util.Tools.namedThreads;
97import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
98import static org.onlab.onos.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -080099import static org.onlab.onos.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700100
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700101// TODO: give me a better name
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700102/**
103 * Manages inventory of infrastructure devices using gossip protocol to distribute
104 * information.
105 */
106@Component(immediate = true)
107@Service
108public class GossipDeviceStore
109 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
110 implements DeviceStore {
111
112 private final Logger log = getLogger(getClass());
113
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700114 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700115
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700116 // innerMap is used to lock a Device, thus instance should never be replaced.
117 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700118 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700119 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700120
121 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700122 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
123 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
124
125 // to be updated under Device lock
126 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
127 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700128
129 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700130 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700131
132 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700133 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700134
Madan Jampani47c93732014-10-06 20:46:08 -0700135 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
136 protected ClusterCommunicationService clusterCommunicator;
137
Madan Jampani53e44e62014-10-07 12:39:51 -0700138 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
139 protected ClusterService clusterService;
140
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700141 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
142 protected MastershipService mastershipService;
143
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800144 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
145 protected MastershipTermService termService;
146
147
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700148 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700149 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700150 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700151 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800152 .register(DistributedStoreSerializers.STORE_COMMON)
153 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
154 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
155 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700156 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800157 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
158 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700159 .register(DeviceAntiEntropyAdvertisement.class)
160 .register(DeviceFragmentId.class)
161 .register(PortFragmentId.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800162 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700163 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700164 };
165
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800166 private ExecutorService executor;
167
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800168 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700169
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800170
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700171 @Activate
172 public void activate() {
Madan Jampani2206e012014-10-06 21:04:20 -0700173 clusterCommunicator.addSubscriber(
174 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener());
175 clusterCommunicator.addSubscriber(
Madan Jampani25322532014-10-08 11:20:38 -0700176 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, new InternalDeviceOfflineEventListener());
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800177 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ, new InternalRemoveRequestListener());
Madan Jampani25322532014-10-08 11:20:38 -0700178 clusterCommunicator.addSubscriber(
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700179 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener());
180 clusterCommunicator.addSubscriber(
Madan Jampani2206e012014-10-06 21:04:20 -0700181 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener());
182 clusterCommunicator.addSubscriber(
183 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700184 clusterCommunicator.addSubscriber(
185 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE, new InternalDeviceAdvertisementListener());
186
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800187 executor = Executors.newCachedThreadPool(namedThreads("device-fg-%d"));
188
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800189 backgroundExecutor =
190 newSingleThreadScheduledExecutor(minPriority(namedThreads("device-bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700191
192 // TODO: Make these configurable
193 long initialDelaySec = 5;
194 long periodSec = 5;
195 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800196 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700197 initialDelaySec, periodSec, TimeUnit.SECONDS);
198
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700199 log.info("Started");
200 }
201
202 @Deactivate
203 public void deactivate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700204
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800205 executor.shutdownNow();
206
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800207 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700208 try {
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800209 boolean timedout = backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700210 if (timedout) {
211 log.error("Timeout during executor shutdown");
212 }
213 } catch (InterruptedException e) {
214 log.error("Error during executor shutdown", e);
215 }
216
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700217 deviceDescs.clear();
218 devices.clear();
219 devicePorts.clear();
220 availableDevices.clear();
221 log.info("Stopped");
222 }
223
224 @Override
225 public int getDeviceCount() {
226 return devices.size();
227 }
228
229 @Override
230 public Iterable<Device> getDevices() {
231 return Collections.unmodifiableCollection(devices.values());
232 }
233
234 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800235 public Iterable<Device> getAvailableDevices() {
236 return FluentIterable.from(getDevices())
237 .filter(new Predicate<Device>() {
238
239 @Override
240 public boolean apply(Device input) {
241 return isAvailable(input.id());
242 }
243 });
244 }
245
246 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700247 public Device getDevice(DeviceId deviceId) {
248 return devices.get(deviceId);
249 }
250
251 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700252 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
253 DeviceId deviceId,
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700254 DeviceDescription deviceDescription) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700255 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700256 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700257 final DeviceEvent event;
258 final Timestamped<DeviceDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800259 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
260 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700261 event = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800262 mergedDesc = device.get(providerId).getDeviceDesc();
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700263 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700264 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700265 log.info("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
266 providerId, deviceId);
267 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700268 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
Madan Jampani47c93732014-10-06 20:46:08 -0700269 } catch (IOException e) {
Madan Jampani25322532014-10-08 11:20:38 -0700270 log.error("Failed to notify peers of a device update topology event for providerId: "
Madan Jampani47c93732014-10-06 20:46:08 -0700271 + providerId + " and deviceId: " + deviceId, e);
272 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700273 }
274 return event;
275 }
276
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700277 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
278 DeviceId deviceId,
279 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700280
281 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800282 Map<ProviderId, DeviceDescriptions> device
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700283 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700284
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800285 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700286 // locking per device
287
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700288 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
289 log.debug("Ignoring outdated event: {}", deltaDesc);
290 return null;
291 }
292
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800293 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700294
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700295 final Device oldDevice = devices.get(deviceId);
296 final Device newDevice;
297
298 if (deltaDesc == descs.getDeviceDesc() ||
299 deltaDesc.isNewer(descs.getDeviceDesc())) {
300 // on new device or valid update
301 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800302 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700303 } else {
304 // outdated event, ignored.
305 return null;
306 }
307 if (oldDevice == null) {
308 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700309 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700310 } else {
311 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700312 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700313 }
314 }
315 }
316
317 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700318 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700319 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700320 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700321
322 // update composed device cache
323 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
324 verify(oldDevice == null,
325 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
326 providerId, oldDevice, newDevice);
327
328 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700329 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700330 }
331
332 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
333 }
334
335 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700336 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700337 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700338 Device oldDevice,
339 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700340 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700341 boolean propertiesChanged =
342 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
343 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion());
344 boolean annotationsChanged =
345 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700346
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700347 // Primary providers can respond to all changes, but ancillary ones
348 // should respond only to annotation changes.
349 if ((providerId.isAncillary() && annotationsChanged) ||
350 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700351 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
352 if (!replaced) {
353 verify(replaced,
354 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
355 providerId, oldDevice, devices.get(newDevice.id())
356 , newDevice);
357 }
358 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700359 markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700360 }
361 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
362 }
363
364 // Otherwise merely attempt to change availability if primary provider
365 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700366 boolean added = markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700367 return !added ? null :
368 new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null);
369 }
370 return null;
371 }
372
373 @Override
374 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700375 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700376 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700377 if (event != null) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700378 log.info("Notifying peers of a device offline topology event for deviceId: {} {}",
379 deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700380 try {
381 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
382 } catch (IOException e) {
383 log.error("Failed to notify peers of a device offline topology event for deviceId: {}",
384 deviceId);
385 }
386 }
387 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700388 }
389
390 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
391
392 Map<ProviderId, DeviceDescriptions> providerDescs
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700393 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700394
395 // locking device
396 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700397
398 // accept off-line if given timestamp is newer than
399 // the latest Timestamp from Primary provider
400 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
401 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
402 if (timestamp.compareTo(lastTimestamp) <= 0) {
403 // outdated event ignore
404 return null;
405 }
406
407 offline.put(deviceId, timestamp);
408
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700409 Device device = devices.get(deviceId);
410 if (device == null) {
411 return null;
412 }
413 boolean removed = availableDevices.remove(deviceId);
414 if (removed) {
415 // TODO: broadcast ... DOWN only?
416 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700417 }
418 return null;
419 }
420 }
421
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700422 /**
423 * Marks the device as available if the given timestamp is not outdated,
424 * compared to the time the device has been marked offline.
425 *
426 * @param deviceId identifier of the device
427 * @param timestamp of the event triggering this change.
428 * @return true if availability change request was accepted and changed the state
429 */
430 // Guarded by deviceDescs value (=Device lock)
431 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
432 // accept on-line if given timestamp is newer than
433 // the latest offline request Timestamp
434 Timestamp offlineTimestamp = offline.get(deviceId);
435 if (offlineTimestamp == null ||
436 offlineTimestamp.compareTo(timestamp) < 0) {
437
438 offline.remove(deviceId);
439 return availableDevices.add(deviceId);
440 }
441 return false;
442 }
443
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700444 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700445 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
446 DeviceId deviceId,
447 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700448
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700449 final Timestamp newTimestamp;
450 try {
451 newTimestamp = deviceClockService.getTimestamp(deviceId);
452 } catch (IllegalStateException e) {
453 log.info("Timestamp was not available for device {}", deviceId);
454 log.debug(" discarding {}", portDescriptions);
455 // Failed to generate timestamp.
456
457 // Possible situation:
458 // Device connected and became master for short period of time,
459 // but lost mastership before this instance had the chance to
460 // retrieve term information.
461
462 // Information dropped here is expected to be recoverable by
463 // device probing after mastership change
464
465 return Collections.emptyList();
466 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800467 log.debug("timestamp for {} {}", deviceId, newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700468
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700469 final Timestamped<List<PortDescription>> timestampedInput
470 = new Timestamped<>(portDescriptions, newTimestamp);
471 final List<DeviceEvent> events;
472 final Timestamped<List<PortDescription>> merged;
473
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800474 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
475 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700476 events = updatePortsInternal(providerId, deviceId, timestampedInput);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800477 final DeviceDescriptions descs = device.get(providerId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700478 List<PortDescription> mergedList =
479 FluentIterable.from(portDescriptions)
480 .transform(new Function<PortDescription, PortDescription>() {
481 @Override
482 public PortDescription apply(PortDescription input) {
483 // lookup merged port description
484 return descs.getPortDesc(input.portNumber()).value();
485 }
486 }).toList();
487 merged = new Timestamped<List<PortDescription>>(mergedList, newTimestamp);
488 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700489 if (!events.isEmpty()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800490 log.info("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Madan Jampani47c93732014-10-06 20:46:08 -0700491 providerId, deviceId);
492 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700493 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
Madan Jampani47c93732014-10-06 20:46:08 -0700494 } catch (IOException e) {
495 log.error("Failed to notify peers of a port update topology event or providerId: "
496 + providerId + " and deviceId: " + deviceId, e);
497 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700498 }
499 return events;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700500 }
501
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700502 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
503 DeviceId deviceId,
504 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700505
506 Device device = devices.get(deviceId);
507 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
508
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700509 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700510 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
511
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700512 List<DeviceEvent> events = new ArrayList<>();
513 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700514
515 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
516 log.debug("Ignoring outdated events: {}", portDescriptions);
517 return null;
518 }
519
520 DeviceDescriptions descs = descsMap.get(providerId);
521 // every provider must provide DeviceDescription.
522 checkArgument(descs != null,
523 "Device description for Device ID %s from Provider %s was not found",
524 deviceId, providerId);
525
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700526 Map<PortNumber, Port> ports = getPortMap(deviceId);
527
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700528 final Timestamp newTimestamp = portDescriptions.timestamp();
529
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700530 // Add new ports
531 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700532 for (PortDescription portDescription : portDescriptions.value()) {
533 final PortNumber number = portDescription.portNumber();
534 processed.add(number);
535
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700536 final Port oldPort = ports.get(number);
537 final Port newPort;
538
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700539
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700540 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
541 if (existingPortDesc == null ||
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700542 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700543 // on new port or valid update
544 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700545 descs.putPortDesc(new Timestamped<>(portDescription,
546 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700547 newPort = composePort(device, number, descsMap);
548 } else {
549 // outdated event, ignored.
550 continue;
551 }
552
553 events.add(oldPort == null ?
554 createPort(device, newPort, ports) :
555 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700556 }
557
558 events.addAll(pruneOldPorts(device, ports, processed));
559 }
560 return FluentIterable.from(events).filter(notNull()).toList();
561 }
562
563 // Creates a new port based on the port description adds it to the map and
564 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700565 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700566 private DeviceEvent createPort(Device device, Port newPort,
567 Map<PortNumber, Port> ports) {
568 ports.put(newPort.number(), newPort);
569 return new DeviceEvent(PORT_ADDED, device, newPort);
570 }
571
572 // Checks if the specified port requires update and if so, it replaces the
573 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700574 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700575 private DeviceEvent updatePort(Device device, Port oldPort,
576 Port newPort,
577 Map<PortNumber, Port> ports) {
578 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700579 oldPort.type() != newPort.type() ||
580 oldPort.portSpeed() != newPort.portSpeed() ||
581 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700582 ports.put(oldPort.number(), newPort);
583 return new DeviceEvent(PORT_UPDATED, device, newPort);
584 }
585 return null;
586 }
587
588 // Prunes the specified list of ports based on which ports are in the
589 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700590 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700591 private List<DeviceEvent> pruneOldPorts(Device device,
592 Map<PortNumber, Port> ports,
593 Set<PortNumber> processed) {
594 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700595 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700596 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700597 Entry<PortNumber, Port> e = iterator.next();
598 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700599 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700600 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700601 iterator.remove();
602 }
603 }
604 return events;
605 }
606
607 // Gets the map of ports for the specified device; if one does not already
608 // exist, it creates and registers a new one.
609 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
610 return createIfAbsentUnchecked(devicePorts, deviceId,
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700611 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
612 }
613
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700614 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700615 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700616 Map<ProviderId, DeviceDescriptions> r;
617 r = deviceDescs.get(deviceId);
618 if (r == null) {
619 r = new HashMap<ProviderId, DeviceDescriptions>();
620 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
621 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
622 if (concurrentlyAdded != null) {
623 r = concurrentlyAdded;
624 }
625 }
626 return r;
627 }
628
629 // Guarded by deviceDescs value (=Device lock)
630 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
631 Map<ProviderId, DeviceDescriptions> device,
632 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
633
634 synchronized (device) {
635 DeviceDescriptions r = device.get(providerId);
636 if (r == null) {
637 r = new DeviceDescriptions(deltaDesc);
638 device.put(providerId, r);
639 }
640 return r;
641 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700642 }
643
644 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700645 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
646 DeviceId deviceId,
647 PortDescription portDescription) {
648
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700649 final Timestamp newTimestamp;
650 try {
651 newTimestamp = deviceClockService.getTimestamp(deviceId);
652 } catch (IllegalStateException e) {
653 log.info("Timestamp was not available for device {}", deviceId);
654 log.debug(" discarding {}", portDescription);
655 // Failed to generate timestamp. Ignoring.
656 // See updatePorts comment
657 return null;
658 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700659 final Timestamped<PortDescription> deltaDesc
660 = new Timestamped<>(portDescription, newTimestamp);
661 final DeviceEvent event;
662 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800663 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
664 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700665 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800666 mergedDesc = device.get(providerId)
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700667 .getPortDesc(portDescription.portNumber());
668 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700669 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700670 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
671 providerId, deviceId);
672 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700673 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Madan Jampani47c93732014-10-06 20:46:08 -0700674 } catch (IOException e) {
675 log.error("Failed to notify peers of a port status update topology event or providerId: "
676 + providerId + " and deviceId: " + deviceId, e);
677 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700678 }
679 return event;
680 }
681
682 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
683 Timestamped<PortDescription> deltaDesc) {
684
685 Device device = devices.get(deviceId);
686 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
687
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700688 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700689 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
690
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700691 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700692
693 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
694 log.debug("Ignoring outdated event: {}", deltaDesc);
695 return null;
696 }
697
698 DeviceDescriptions descs = descsMap.get(providerId);
699 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700700 verify(descs != null,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700701 "Device description for Device ID %s from Provider %s was not found",
702 deviceId, providerId);
703
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700704 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
705 final PortNumber number = deltaDesc.value().portNumber();
706 final Port oldPort = ports.get(number);
707 final Port newPort;
708
709 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
710 if (existingPortDesc == null ||
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700711 deltaDesc.isNewer(existingPortDesc)) {
712 // on new port or valid update
713 // update description
714 descs.putPortDesc(deltaDesc);
715 newPort = composePort(device, number, descsMap);
716 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700717 // same or outdated event, ignored.
718 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700719 return null;
720 }
721
722 if (oldPort == null) {
723 return createPort(device, newPort, ports);
724 } else {
725 return updatePort(device, oldPort, newPort, ports);
726 }
727 }
728 }
729
730 @Override
731 public List<Port> getPorts(DeviceId deviceId) {
732 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
733 if (ports == null) {
734 return Collections.emptyList();
735 }
736 return ImmutableList.copyOf(ports.values());
737 }
738
739 @Override
740 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
741 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
742 return ports == null ? null : ports.get(portNumber);
743 }
744
745 @Override
746 public boolean isAvailable(DeviceId deviceId) {
747 return availableDevices.contains(deviceId);
748 }
749
750 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700751 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800752 final NodeId myId = clusterService.getLocalNode().id();
753 NodeId master = mastershipService.getMasterFor(deviceId);
754
755 // if there exist a master, forward
756 // if there is no master, try to become one and process
757
758 boolean relinquishAtEnd = false;
759 if (master == null) {
760 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
761 if (myRole != MastershipRole.NONE) {
762 relinquishAtEnd = true;
763 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800764 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800765 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800766 MastershipTerm term = termService.getMastershipTerm(deviceId);
767 if (myId.equals(term.master())) {
768 master = myId;
769 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700770 }
771
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800772 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800773 log.debug("{} has control of {}, forwarding remove request",
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800774 master, deviceId);
775
776 ClusterMessage message = new ClusterMessage(
777 myId,
778 DEVICE_REMOVE_REQ,
779 SERIALIZER.encode(deviceId));
780
781 try {
782 clusterCommunicator.unicast(message, master);
783 } catch (IOException e) {
784 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
785 }
786
787 // event will be triggered after master processes it.
788 return null;
789 }
790
791 // I have control..
792
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700793 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700794 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700795 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800796 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700797 deviceId);
798 try {
799 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
800 } catch (IOException e) {
801 log.error("Failed to notify peers of a device removed topology event for deviceId: {}",
802 deviceId);
803 }
804 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800805 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800806 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800807 mastershipService.relinquishMastership(deviceId);
808 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700809 return event;
810 }
811
812 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
813 Timestamp timestamp) {
814
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700815 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700816 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700817 // accept removal request if given timestamp is newer than
818 // the latest Timestamp from Primary provider
819 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
820 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
821 if (timestamp.compareTo(lastTimestamp) <= 0) {
822 // outdated event ignore
823 return null;
824 }
825 removalRequest.put(deviceId, timestamp);
826
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700827 Device device = devices.remove(deviceId);
828 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700829 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
830 if (ports != null) {
831 ports.clear();
832 }
833 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700834 descs.clear();
835 return device == null ? null :
836 new DeviceEvent(DEVICE_REMOVED, device, null);
837 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700838 }
839
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700840 /**
841 * Checks if given timestamp is superseded by removal request
842 * with more recent timestamp.
843 *
844 * @param deviceId identifier of a device
845 * @param timestampToCheck timestamp of an event to check
846 * @return true if device is already removed
847 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700848 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
849 Timestamp removalTimestamp = removalRequest.get(deviceId);
850 if (removalTimestamp != null &&
851 removalTimestamp.compareTo(timestampToCheck) >= 0) {
852 // removalRequest is more recent
853 return true;
854 }
855 return false;
856 }
857
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700858 /**
859 * Returns a Device, merging description given from multiple Providers.
860 *
861 * @param deviceId device identifier
862 * @param providerDescs Collection of Descriptions from multiple providers
863 * @return Device instance
864 */
865 private Device composeDevice(DeviceId deviceId,
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700866 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700867
Thomas Vachuska444eda62014-10-28 13:09:42 -0700868 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700869
870 ProviderId primary = pickPrimaryPID(providerDescs);
871
872 DeviceDescriptions desc = providerDescs.get(primary);
873
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700874 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700875 Type type = base.type();
876 String manufacturer = base.manufacturer();
877 String hwVersion = base.hwVersion();
878 String swVersion = base.swVersion();
879 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700880 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700881 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
882 annotations = merge(annotations, base.annotations());
883
884 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
885 if (e.getKey().equals(primary)) {
886 continue;
887 }
888 // TODO: should keep track of Description timestamp
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700889 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700890 // Currently assuming there will never be a key conflict between
891 // providers
892
893 // annotation merging. not so efficient, should revisit later
894 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
895 }
896
897 return new DefaultDevice(primary, deviceId , type, manufacturer,
alshabib7911a052014-10-16 17:49:37 -0700898 hwVersion, swVersion, serialNumber,
899 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700900 }
901
902 /**
903 * Returns a Port, merging description given from multiple Providers.
904 *
905 * @param device device the port is on
906 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700907 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700908 * @return Port instance
909 */
910 private Port composePort(Device device, PortNumber number,
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700911 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700912
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700913 ProviderId primary = pickPrimaryPID(descsMap);
914 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700915 // if no primary, assume not enabled
916 // TODO: revisit this default port enabled/disabled behavior
917 boolean isEnabled = false;
918 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
919
920 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
921 if (portDesc != null) {
922 isEnabled = portDesc.value().isEnabled();
923 annotations = merge(annotations, portDesc.value().annotations());
924 }
925
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700926 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700927 if (e.getKey().equals(primary)) {
928 continue;
929 }
930 // TODO: should keep track of Description timestamp
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700931 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700932 // Currently assuming there will never be a key conflict between
933 // providers
934
935 // annotation merging. not so efficient, should revisit later
936 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
937 if (otherPortDesc != null) {
938 annotations = merge(annotations, otherPortDesc.value().annotations());
939 }
940 }
941
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700942 return portDesc == null ?
943 new DefaultPort(device, number, false, annotations) :
944 new DefaultPort(device, number, isEnabled, portDesc.value().type(),
945 portDesc.value().portSpeed(), annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700946 }
947
948 /**
949 * @return primary ProviderID, or randomly chosen one if none exists
950 */
951 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700952 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700953 ProviderId fallBackPrimary = null;
954 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
955 if (!e.getKey().isAncillary()) {
956 return e.getKey();
957 } else if (fallBackPrimary == null) {
958 // pick randomly as a fallback in case there is no primary
959 fallBackPrimary = e.getKey();
960 }
961 }
962 return fallBackPrimary;
963 }
964
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700965 private DeviceDescriptions getPrimaryDescriptions(
966 Map<ProviderId, DeviceDescriptions> providerDescs) {
967 ProviderId pid = pickPrimaryPID(providerDescs);
968 return providerDescs.get(pid);
969 }
970
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700971 // TODO: should we be throwing exception?
972 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
973 ClusterMessage message = new ClusterMessage(
974 clusterService.getLocalNode().id(),
975 subject,
976 SERIALIZER.encode(event));
977 clusterCommunicator.unicast(message, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700978 }
979
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700980 // TODO: should we be throwing exception?
981 private void broadcastMessage(MessageSubject subject, Object event) throws IOException {
982 ClusterMessage message = new ClusterMessage(
983 clusterService.getLocalNode().id(),
984 subject,
985 SERIALIZER.encode(event));
986 clusterCommunicator.broadcast(message);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700987 }
Madan Jampani47c93732014-10-06 20:46:08 -0700988
989 private void notifyPeers(InternalDeviceEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700990 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -0700991 }
992
Madan Jampani25322532014-10-08 11:20:38 -0700993 private void notifyPeers(InternalDeviceOfflineEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700994 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -0700995 }
996
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700997 private void notifyPeers(InternalDeviceRemovedEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700998 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700999 }
1000
Madan Jampani47c93732014-10-06 20:46:08 -07001001 private void notifyPeers(InternalPortEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001002 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001003 }
1004
1005 private void notifyPeers(InternalPortStatusEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001006 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1007 }
1008
1009 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1010 try {
1011 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1012 } catch (IOException e) {
1013 log.error("Failed to send" + event + " to " + recipient, e);
1014 }
1015 }
1016
1017 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1018 try {
1019 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1020 } catch (IOException e) {
1021 log.error("Failed to send" + event + " to " + recipient, e);
1022 }
1023 }
1024
1025 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1026 try {
1027 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1028 } catch (IOException e) {
1029 log.error("Failed to send" + event + " to " + recipient, e);
1030 }
1031 }
1032
1033 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1034 try {
1035 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1036 } catch (IOException e) {
1037 log.error("Failed to send" + event + " to " + recipient, e);
1038 }
1039 }
1040
1041 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1042 try {
1043 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1044 } catch (IOException e) {
1045 log.error("Failed to send" + event + " to " + recipient, e);
1046 }
1047 }
1048
1049 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1050 final NodeId self = clusterService.getLocalNode().id();
1051
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001052 final int numDevices = deviceDescs.size();
1053 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1054 final int portsPerDevice = 8; // random factor to minimize reallocation
1055 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1056 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001057
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001058 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001059
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001060 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001061 synchronized (devDescs) {
1062
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001063 // send device offline timestamp
1064 Timestamp lOffline = this.offline.get(deviceId);
1065 if (lOffline != null) {
1066 adOffline.put(deviceId, lOffline);
1067 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001068
1069 for (Entry<ProviderId, DeviceDescriptions>
1070 prov : devDescs.entrySet()) {
1071
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001072 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001073 final ProviderId provId = prov.getKey();
1074 final DeviceDescriptions descs = prov.getValue();
1075
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001076 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001077 descs.getDeviceDesc().timestamp());
1078
1079 for (Entry<PortNumber, Timestamped<PortDescription>>
1080 portDesc : descs.getPortDescs().entrySet()) {
1081
1082 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001083 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001084 portDesc.getValue().timestamp());
1085 }
1086 }
1087 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001088 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001089
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001090 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001091 }
1092
1093 /**
1094 * Responds to anti-entropy advertisement message.
1095 * <P>
1096 * Notify sender about out-dated information using regular replication message.
1097 * Send back advertisement to sender if not in sync.
1098 *
1099 * @param advertisement to respond to
1100 */
1101 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1102
1103 final NodeId sender = advertisement.sender();
1104
1105 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1106 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1107 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1108
1109 // Fragments to request
1110 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1111 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1112
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001113 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001114 final DeviceId deviceId = de.getKey();
1115 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1116
1117 synchronized (lDevice) {
1118 // latestTimestamp across provider
1119 // Note: can be null initially
1120 Timestamp localLatest = offline.get(deviceId);
1121
1122 // handle device Ads
1123 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1124 final ProviderId provId = prov.getKey();
1125 final DeviceDescriptions lDeviceDescs = prov.getValue();
1126
1127 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1128
1129
1130 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1131 Timestamp advDevTimestamp = devAds.get(devFragId);
1132
1133 if (advDevTimestamp == null || lProvDevice.isNewer(advDevTimestamp)) {
1134 // remote does not have it or outdated, suggest
1135 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1136 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1137 // local is outdated, request
1138 reqDevices.add(devFragId);
1139 }
1140
1141 // handle port Ads
1142 for (Entry<PortNumber, Timestamped<PortDescription>>
1143 pe : lDeviceDescs.getPortDescs().entrySet()) {
1144
1145 final PortNumber num = pe.getKey();
1146 final Timestamped<PortDescription> lPort = pe.getValue();
1147
1148 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1149
1150 Timestamp advPortTimestamp = portAds.get(portFragId);
Yuta HIGUCHIec76bfe2014-10-09 20:17:07 -07001151 if (advPortTimestamp == null || lPort.isNewer(advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001152 // remote does not have it or outdated, suggest
1153 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1154 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1155 // local is outdated, request
1156 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1157 reqPorts.add(portFragId);
1158 }
1159
1160 // remove port Ad already processed
1161 portAds.remove(portFragId);
1162 } // end local port loop
1163
1164 // remove device Ad already processed
1165 devAds.remove(devFragId);
1166
1167 // find latest and update
1168 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1169 if (localLatest == null ||
1170 providerLatest.compareTo(localLatest) > 0) {
1171 localLatest = providerLatest;
1172 }
1173 } // end local provider loop
1174
1175 // checking if remote timestamp is more recent.
1176 Timestamp rOffline = offlineAds.get(deviceId);
1177 if (rOffline != null &&
1178 rOffline.compareTo(localLatest) > 0) {
1179 // remote offline timestamp suggests that the
1180 // device is off-line
1181 markOfflineInternal(deviceId, rOffline);
1182 }
1183
1184 Timestamp lOffline = offline.get(deviceId);
1185 if (lOffline != null && rOffline == null) {
1186 // locally offline, but remote is online, suggest offline
1187 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1188 }
1189
1190 // remove device offline Ad already processed
1191 offlineAds.remove(deviceId);
1192 } // end local device loop
1193 } // device lock
1194
1195 // If there is any Ads left, request them
1196 log.trace("Ads left {}, {}", devAds, portAds);
1197 reqDevices.addAll(devAds.keySet());
1198 reqPorts.addAll(portAds.keySet());
1199
1200 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1201 log.trace("Nothing to request to remote peer {}", sender);
1202 return;
1203 }
1204
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001205 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001206
1207 // 2-way Anti-Entropy for now
1208 try {
1209 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1210 } catch (IOException e) {
1211 log.error("Failed to send response advertisement to " + sender, e);
1212 }
1213
1214// Sketch of 3-way Anti-Entropy
1215// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1216// ClusterMessage message = new ClusterMessage(
1217// clusterService.getLocalNode().id(),
1218// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1219// SERIALIZER.encode(request));
1220//
1221// try {
1222// clusterCommunicator.unicast(message, advertisement.sender());
1223// } catch (IOException e) {
1224// log.error("Failed to send advertisement reply to "
1225// + advertisement.sender(), e);
1226// }
Madan Jampani47c93732014-10-06 20:46:08 -07001227 }
1228
Madan Jampani255a58b2014-10-09 12:08:20 -07001229 private void notifyDelegateIfNotNull(DeviceEvent event) {
1230 if (event != null) {
1231 notifyDelegate(event);
1232 }
1233 }
1234
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001235 private final class SendAdvertisementTask implements Runnable {
1236
1237 @Override
1238 public void run() {
1239 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001240 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001241 return;
1242 }
1243
1244 try {
1245 final NodeId self = clusterService.getLocalNode().id();
1246 Set<ControllerNode> nodes = clusterService.getNodes();
1247
1248 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1249 .transform(toNodeId())
1250 .toList();
1251
1252 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001253 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001254 return;
1255 }
1256
1257 NodeId peer;
1258 do {
1259 int idx = RandomUtils.nextInt(0, nodeIds.size());
1260 peer = nodeIds.get(idx);
1261 } while (peer.equals(self));
1262
1263 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1264
1265 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001266 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001267 return;
1268 }
1269
1270 try {
1271 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1272 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001273 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001274 return;
1275 }
1276 } catch (Exception e) {
1277 // catch all Exception to avoid Scheduled task being suppressed.
1278 log.error("Exception thrown while sending advertisement", e);
1279 }
1280 }
1281 }
1282
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001283 private final class InternalDeviceEventListener
1284 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001285 @Override
1286 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001287
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001288 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001289 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001290
Madan Jampani47c93732014-10-06 20:46:08 -07001291 ProviderId providerId = event.providerId();
1292 DeviceId deviceId = event.deviceId();
1293 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001294
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001295 executor.submit(new Runnable() {
1296
1297 @Override
1298 public void run() {
1299 try {
1300 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1301 } catch (Exception e) {
1302 log.warn("Exception thrown handling device update", e);
1303 }
1304 }
1305 });
Madan Jampani47c93732014-10-06 20:46:08 -07001306 }
1307 }
1308
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001309 private final class InternalDeviceOfflineEventListener
1310 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001311 @Override
1312 public void handle(ClusterMessage message) {
1313
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001314 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001315 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001316
1317 DeviceId deviceId = event.deviceId();
1318 Timestamp timestamp = event.timestamp();
1319
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001320 executor.submit(new Runnable() {
1321
1322 @Override
1323 public void run() {
1324 try {
1325 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1326 } catch (Exception e) {
1327 log.warn("Exception thrown handling device offline", e);
1328 }
1329 }
1330 });
Madan Jampani25322532014-10-08 11:20:38 -07001331 }
1332 }
1333
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001334 private final class InternalRemoveRequestListener
1335 implements ClusterMessageHandler {
1336 @Override
1337 public void handle(ClusterMessage message) {
1338 log.debug("Received device remove request from peer: {}", message.sender());
1339 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001340
1341 executor.submit(new Runnable() {
1342
1343 @Override
1344 public void run() {
1345 try {
1346 removeDevice(did);
1347 } catch (Exception e) {
1348 log.warn("Exception thrown handling device remove", e);
1349 }
1350 }
1351 });
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001352 }
1353 }
1354
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001355 private final class InternalDeviceRemovedEventListener
1356 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001357 @Override
1358 public void handle(ClusterMessage message) {
1359
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001360 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001361 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001362
1363 DeviceId deviceId = event.deviceId();
1364 Timestamp timestamp = event.timestamp();
1365
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001366 executor.submit(new Runnable() {
1367
1368 @Override
1369 public void run() {
1370 try {
1371 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1372 } catch (Exception e) {
1373 log.warn("Exception thrown handling device removed", e);
1374 }
1375 }
1376 });
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001377 }
1378 }
1379
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001380 private final class InternalPortEventListener
1381 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001382 @Override
1383 public void handle(ClusterMessage message) {
1384
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001385 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001386 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001387
1388 ProviderId providerId = event.providerId();
1389 DeviceId deviceId = event.deviceId();
1390 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1391
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001392 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001393 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001394 // Note: dropped information will be recovered by anti-entropy
1395 return;
1396 }
1397
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001398 executor.submit(new Runnable() {
1399
1400 @Override
1401 public void run() {
1402 try {
1403 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1404 } catch (Exception e) {
1405 log.warn("Exception thrown handling port update", e);
1406 }
1407 }
1408 });
Madan Jampani47c93732014-10-06 20:46:08 -07001409 }
1410 }
1411
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001412 private final class InternalPortStatusEventListener
1413 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001414 @Override
1415 public void handle(ClusterMessage message) {
1416
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001417 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001418 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001419
1420 ProviderId providerId = event.providerId();
1421 DeviceId deviceId = event.deviceId();
1422 Timestamped<PortDescription> portDescription = event.portDescription();
1423
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001424 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001425 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001426 // Note: dropped information will be recovered by anti-entropy
1427 return;
1428 }
1429
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001430 executor.submit(new Runnable() {
1431
1432 @Override
1433 public void run() {
1434 try {
1435 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1436 } catch (Exception e) {
1437 log.warn("Exception thrown handling port update", e);
1438 }
1439 }
1440 });
Madan Jampani47c93732014-10-06 20:46:08 -07001441 }
1442 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001443
1444 private final class InternalDeviceAdvertisementListener
1445 implements ClusterMessageHandler {
1446
1447 @Override
1448 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001449 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001450 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Yuta HIGUCHI06586272014-11-25 14:27:03 -08001451 backgroundExecutor.submit(new Runnable() {
1452
1453 @Override
1454 public void run() {
1455 try {
1456 handleAdvertisement(advertisement);
1457 } catch (Exception e) {
1458 log.warn("Exception thrown handling Device advertisements.", e);
1459 }
1460 }
1461 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001462 }
1463 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001464}