blob: 78838d0a2b381e6375b169d6aa1f07b9b0841aa5 [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 HIGUCHI80d56592014-11-25 15:11:13 -080081import java.util.concurrent.ExecutorService;
82import java.util.concurrent.Executors;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070083import java.util.concurrent.ScheduledExecutorService;
84import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070085
86import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070087import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHIdc7374c2014-10-10 11:11:09 -070088import static org.onlab.onos.cluster.ControllerNodeToNodeId.toNodeId;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070089import static org.onlab.onos.net.device.DeviceEvent.Type.*;
90import static org.slf4j.LoggerFactory.getLogger;
91import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
92import static org.onlab.onos.net.DefaultAnnotations.merge;
93import static com.google.common.base.Verify.verify;
Yuta HIGUCHI06586272014-11-25 14:27:03 -080094import static org.onlab.util.Tools.minPriority;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070095import static org.onlab.util.Tools.namedThreads;
96import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
97import static org.onlab.onos.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -080098import static org.onlab.onos.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070099
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700100// TODO: give me a better name
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700101/**
102 * Manages inventory of infrastructure devices using gossip protocol to distribute
103 * information.
104 */
105@Component(immediate = true)
106@Service
107public class GossipDeviceStore
108 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
109 implements DeviceStore {
110
111 private final Logger log = getLogger(getClass());
112
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700113 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700114
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700115 // innerMap is used to lock a Device, thus instance should never be replaced.
116 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700117 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700118 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700119
120 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700121 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
122 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
123
124 // to be updated under Device lock
125 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
126 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700127
128 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700129 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700130
131 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700132 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700133
Madan Jampani47c93732014-10-06 20:46:08 -0700134 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
135 protected ClusterCommunicationService clusterCommunicator;
136
Madan Jampani53e44e62014-10-07 12:39:51 -0700137 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
138 protected ClusterService clusterService;
139
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700140 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
141 protected MastershipService mastershipService;
142
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800143 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
144 protected MastershipTermService termService;
145
146
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700147 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700148 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700149 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700150 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800151 .register(DistributedStoreSerializers.STORE_COMMON)
152 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
153 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
154 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700155 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800156 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
157 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700158 .register(DeviceAntiEntropyAdvertisement.class)
159 .register(DeviceFragmentId.class)
160 .register(PortFragmentId.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800161 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700162 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700163 };
164
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800165 private ExecutorService executor;
166
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800167 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700168
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800169
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700170 @Activate
171 public void activate() {
Madan Jampani2206e012014-10-06 21:04:20 -0700172 clusterCommunicator.addSubscriber(
173 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener());
174 clusterCommunicator.addSubscriber(
Madan Jampani25322532014-10-08 11:20:38 -0700175 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, new InternalDeviceOfflineEventListener());
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800176 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ, new InternalRemoveRequestListener());
Madan Jampani25322532014-10-08 11:20:38 -0700177 clusterCommunicator.addSubscriber(
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700178 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener());
179 clusterCommunicator.addSubscriber(
Madan Jampani2206e012014-10-06 21:04:20 -0700180 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener());
181 clusterCommunicator.addSubscriber(
182 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700183 clusterCommunicator.addSubscriber(
184 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE, new InternalDeviceAdvertisementListener());
185
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800186 executor = Executors.newCachedThreadPool(namedThreads("device-fg-%d"));
187
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800188 backgroundExecutor =
189 newSingleThreadScheduledExecutor(minPriority(namedThreads("device-bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700190
191 // TODO: Make these configurable
192 long initialDelaySec = 5;
193 long periodSec = 5;
194 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800195 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700196 initialDelaySec, periodSec, TimeUnit.SECONDS);
197
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700198 log.info("Started");
199 }
200
201 @Deactivate
202 public void deactivate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700203
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800204 executor.shutdownNow();
205
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800206 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700207 try {
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800208 boolean timedout = backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700209 if (timedout) {
210 log.error("Timeout during executor shutdown");
211 }
212 } catch (InterruptedException e) {
213 log.error("Error during executor shutdown", e);
214 }
215
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700216 deviceDescs.clear();
217 devices.clear();
218 devicePorts.clear();
219 availableDevices.clear();
220 log.info("Stopped");
221 }
222
223 @Override
224 public int getDeviceCount() {
225 return devices.size();
226 }
227
228 @Override
229 public Iterable<Device> getDevices() {
230 return Collections.unmodifiableCollection(devices.values());
231 }
232
233 @Override
234 public Device getDevice(DeviceId deviceId) {
235 return devices.get(deviceId);
236 }
237
238 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700239 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
240 DeviceId deviceId,
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700241 DeviceDescription deviceDescription) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700242 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700243 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700244 final DeviceEvent event;
245 final Timestamped<DeviceDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800246 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
247 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700248 event = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800249 mergedDesc = device.get(providerId).getDeviceDesc();
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700250 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700251 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700252 log.info("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
253 providerId, deviceId);
254 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700255 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
Madan Jampani47c93732014-10-06 20:46:08 -0700256 } catch (IOException e) {
Madan Jampani25322532014-10-08 11:20:38 -0700257 log.error("Failed to notify peers of a device update topology event for providerId: "
Madan Jampani47c93732014-10-06 20:46:08 -0700258 + providerId + " and deviceId: " + deviceId, e);
259 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700260 }
261 return event;
262 }
263
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700264 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
265 DeviceId deviceId,
266 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700267
268 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800269 Map<ProviderId, DeviceDescriptions> device
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700270 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700271
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800272 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700273 // locking per device
274
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700275 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
276 log.debug("Ignoring outdated event: {}", deltaDesc);
277 return null;
278 }
279
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800280 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700281
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700282 final Device oldDevice = devices.get(deviceId);
283 final Device newDevice;
284
285 if (deltaDesc == descs.getDeviceDesc() ||
286 deltaDesc.isNewer(descs.getDeviceDesc())) {
287 // on new device or valid update
288 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800289 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700290 } else {
291 // outdated event, ignored.
292 return null;
293 }
294 if (oldDevice == null) {
295 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700296 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700297 } else {
298 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700299 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700300 }
301 }
302 }
303
304 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700305 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700306 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700307 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700308
309 // update composed device cache
310 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
311 verify(oldDevice == null,
312 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
313 providerId, oldDevice, newDevice);
314
315 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700316 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700317 }
318
319 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
320 }
321
322 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700323 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700324 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700325 Device oldDevice,
326 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700327 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700328 boolean propertiesChanged =
329 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
330 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion());
331 boolean annotationsChanged =
332 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700333
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700334 // Primary providers can respond to all changes, but ancillary ones
335 // should respond only to annotation changes.
336 if ((providerId.isAncillary() && annotationsChanged) ||
337 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700338 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
339 if (!replaced) {
340 verify(replaced,
341 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
342 providerId, oldDevice, devices.get(newDevice.id())
343 , newDevice);
344 }
345 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700346 markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700347 }
348 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
349 }
350
351 // Otherwise merely attempt to change availability if primary provider
352 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700353 boolean added = markOnline(newDevice.id(), newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700354 return !added ? null :
355 new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null);
356 }
357 return null;
358 }
359
360 @Override
361 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700362 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700363 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700364 if (event != null) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700365 log.info("Notifying peers of a device offline topology event for deviceId: {} {}",
366 deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700367 try {
368 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
369 } catch (IOException e) {
370 log.error("Failed to notify peers of a device offline topology event for deviceId: {}",
371 deviceId);
372 }
373 }
374 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700375 }
376
377 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
378
379 Map<ProviderId, DeviceDescriptions> providerDescs
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700380 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700381
382 // locking device
383 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700384
385 // accept off-line if given timestamp is newer than
386 // the latest Timestamp from Primary provider
387 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
388 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
389 if (timestamp.compareTo(lastTimestamp) <= 0) {
390 // outdated event ignore
391 return null;
392 }
393
394 offline.put(deviceId, timestamp);
395
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700396 Device device = devices.get(deviceId);
397 if (device == null) {
398 return null;
399 }
400 boolean removed = availableDevices.remove(deviceId);
401 if (removed) {
402 // TODO: broadcast ... DOWN only?
403 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700404 }
405 return null;
406 }
407 }
408
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700409 /**
410 * Marks the device as available if the given timestamp is not outdated,
411 * compared to the time the device has been marked offline.
412 *
413 * @param deviceId identifier of the device
414 * @param timestamp of the event triggering this change.
415 * @return true if availability change request was accepted and changed the state
416 */
417 // Guarded by deviceDescs value (=Device lock)
418 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
419 // accept on-line if given timestamp is newer than
420 // the latest offline request Timestamp
421 Timestamp offlineTimestamp = offline.get(deviceId);
422 if (offlineTimestamp == null ||
423 offlineTimestamp.compareTo(timestamp) < 0) {
424
425 offline.remove(deviceId);
426 return availableDevices.add(deviceId);
427 }
428 return false;
429 }
430
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700431 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700432 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
433 DeviceId deviceId,
434 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700435
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700436 final Timestamp newTimestamp;
437 try {
438 newTimestamp = deviceClockService.getTimestamp(deviceId);
439 } catch (IllegalStateException e) {
440 log.info("Timestamp was not available for device {}", deviceId);
441 log.debug(" discarding {}", portDescriptions);
442 // Failed to generate timestamp.
443
444 // Possible situation:
445 // Device connected and became master for short period of time,
446 // but lost mastership before this instance had the chance to
447 // retrieve term information.
448
449 // Information dropped here is expected to be recoverable by
450 // device probing after mastership change
451
452 return Collections.emptyList();
453 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800454 log.debug("timestamp for {} {}", deviceId, newTimestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700455
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700456 final Timestamped<List<PortDescription>> timestampedInput
457 = new Timestamped<>(portDescriptions, newTimestamp);
458 final List<DeviceEvent> events;
459 final Timestamped<List<PortDescription>> merged;
460
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800461 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
462 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700463 events = updatePortsInternal(providerId, deviceId, timestampedInput);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800464 final DeviceDescriptions descs = device.get(providerId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700465 List<PortDescription> mergedList =
466 FluentIterable.from(portDescriptions)
467 .transform(new Function<PortDescription, PortDescription>() {
468 @Override
469 public PortDescription apply(PortDescription input) {
470 // lookup merged port description
471 return descs.getPortDesc(input.portNumber()).value();
472 }
473 }).toList();
474 merged = new Timestamped<List<PortDescription>>(mergedList, newTimestamp);
475 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700476 if (!events.isEmpty()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800477 log.info("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Madan Jampani47c93732014-10-06 20:46:08 -0700478 providerId, deviceId);
479 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700480 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
Madan Jampani47c93732014-10-06 20:46:08 -0700481 } catch (IOException e) {
482 log.error("Failed to notify peers of a port update topology event or providerId: "
483 + providerId + " and deviceId: " + deviceId, e);
484 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700485 }
486 return events;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700487 }
488
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700489 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
490 DeviceId deviceId,
491 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700492
493 Device device = devices.get(deviceId);
494 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
495
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700496 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700497 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
498
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700499 List<DeviceEvent> events = new ArrayList<>();
500 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700501
502 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
503 log.debug("Ignoring outdated events: {}", portDescriptions);
504 return null;
505 }
506
507 DeviceDescriptions descs = descsMap.get(providerId);
508 // every provider must provide DeviceDescription.
509 checkArgument(descs != null,
510 "Device description for Device ID %s from Provider %s was not found",
511 deviceId, providerId);
512
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700513 Map<PortNumber, Port> ports = getPortMap(deviceId);
514
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700515 final Timestamp newTimestamp = portDescriptions.timestamp();
516
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700517 // Add new ports
518 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700519 for (PortDescription portDescription : portDescriptions.value()) {
520 final PortNumber number = portDescription.portNumber();
521 processed.add(number);
522
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700523 final Port oldPort = ports.get(number);
524 final Port newPort;
525
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700526
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700527 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
528 if (existingPortDesc == null ||
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700529 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700530 // on new port or valid update
531 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700532 descs.putPortDesc(new Timestamped<>(portDescription,
533 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700534 newPort = composePort(device, number, descsMap);
535 } else {
536 // outdated event, ignored.
537 continue;
538 }
539
540 events.add(oldPort == null ?
541 createPort(device, newPort, ports) :
542 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700543 }
544
545 events.addAll(pruneOldPorts(device, ports, processed));
546 }
547 return FluentIterable.from(events).filter(notNull()).toList();
548 }
549
550 // Creates a new port based on the port description adds it to the map and
551 // 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 createPort(Device device, Port newPort,
554 Map<PortNumber, Port> ports) {
555 ports.put(newPort.number(), newPort);
556 return new DeviceEvent(PORT_ADDED, device, newPort);
557 }
558
559 // Checks if the specified port requires update and if so, it replaces the
560 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700561 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700562 private DeviceEvent updatePort(Device device, Port oldPort,
563 Port newPort,
564 Map<PortNumber, Port> ports) {
565 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700566 oldPort.type() != newPort.type() ||
567 oldPort.portSpeed() != newPort.portSpeed() ||
568 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700569 ports.put(oldPort.number(), newPort);
570 return new DeviceEvent(PORT_UPDATED, device, newPort);
571 }
572 return null;
573 }
574
575 // Prunes the specified list of ports based on which ports are in the
576 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700577 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700578 private List<DeviceEvent> pruneOldPorts(Device device,
579 Map<PortNumber, Port> ports,
580 Set<PortNumber> processed) {
581 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700582 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700583 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700584 Entry<PortNumber, Port> e = iterator.next();
585 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700586 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700587 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700588 iterator.remove();
589 }
590 }
591 return events;
592 }
593
594 // Gets the map of ports for the specified device; if one does not already
595 // exist, it creates and registers a new one.
596 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
597 return createIfAbsentUnchecked(devicePorts, deviceId,
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700598 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
599 }
600
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700601 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700602 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700603 Map<ProviderId, DeviceDescriptions> r;
604 r = deviceDescs.get(deviceId);
605 if (r == null) {
606 r = new HashMap<ProviderId, DeviceDescriptions>();
607 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
608 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
609 if (concurrentlyAdded != null) {
610 r = concurrentlyAdded;
611 }
612 }
613 return r;
614 }
615
616 // Guarded by deviceDescs value (=Device lock)
617 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
618 Map<ProviderId, DeviceDescriptions> device,
619 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
620
621 synchronized (device) {
622 DeviceDescriptions r = device.get(providerId);
623 if (r == null) {
624 r = new DeviceDescriptions(deltaDesc);
625 device.put(providerId, r);
626 }
627 return r;
628 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700629 }
630
631 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700632 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
633 DeviceId deviceId,
634 PortDescription portDescription) {
635
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700636 final Timestamp newTimestamp;
637 try {
638 newTimestamp = deviceClockService.getTimestamp(deviceId);
639 } catch (IllegalStateException e) {
640 log.info("Timestamp was not available for device {}", deviceId);
641 log.debug(" discarding {}", portDescription);
642 // Failed to generate timestamp. Ignoring.
643 // See updatePorts comment
644 return null;
645 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700646 final Timestamped<PortDescription> deltaDesc
647 = new Timestamped<>(portDescription, newTimestamp);
648 final DeviceEvent event;
649 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800650 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
651 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700652 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800653 mergedDesc = device.get(providerId)
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700654 .getPortDesc(portDescription.portNumber());
655 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700656 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700657 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
658 providerId, deviceId);
659 try {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700660 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Madan Jampani47c93732014-10-06 20:46:08 -0700661 } catch (IOException e) {
662 log.error("Failed to notify peers of a port status update topology event or providerId: "
663 + providerId + " and deviceId: " + deviceId, e);
664 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700665 }
666 return event;
667 }
668
669 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
670 Timestamped<PortDescription> deltaDesc) {
671
672 Device device = devices.get(deviceId);
673 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
674
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700675 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700676 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
677
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700678 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700679
680 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
681 log.debug("Ignoring outdated event: {}", deltaDesc);
682 return null;
683 }
684
685 DeviceDescriptions descs = descsMap.get(providerId);
686 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700687 verify(descs != null,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700688 "Device description for Device ID %s from Provider %s was not found",
689 deviceId, providerId);
690
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700691 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
692 final PortNumber number = deltaDesc.value().portNumber();
693 final Port oldPort = ports.get(number);
694 final Port newPort;
695
696 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
697 if (existingPortDesc == null ||
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700698 deltaDesc.isNewer(existingPortDesc)) {
699 // on new port or valid update
700 // update description
701 descs.putPortDesc(deltaDesc);
702 newPort = composePort(device, number, descsMap);
703 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700704 // same or outdated event, ignored.
705 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700706 return null;
707 }
708
709 if (oldPort == null) {
710 return createPort(device, newPort, ports);
711 } else {
712 return updatePort(device, oldPort, newPort, ports);
713 }
714 }
715 }
716
717 @Override
718 public List<Port> getPorts(DeviceId deviceId) {
719 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
720 if (ports == null) {
721 return Collections.emptyList();
722 }
723 return ImmutableList.copyOf(ports.values());
724 }
725
726 @Override
727 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
728 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
729 return ports == null ? null : ports.get(portNumber);
730 }
731
732 @Override
733 public boolean isAvailable(DeviceId deviceId) {
734 return availableDevices.contains(deviceId);
735 }
736
737 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700738 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800739 final NodeId myId = clusterService.getLocalNode().id();
740 NodeId master = mastershipService.getMasterFor(deviceId);
741
742 // if there exist a master, forward
743 // if there is no master, try to become one and process
744
745 boolean relinquishAtEnd = false;
746 if (master == null) {
747 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
748 if (myRole != MastershipRole.NONE) {
749 relinquishAtEnd = true;
750 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800751 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800752 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800753 MastershipTerm term = termService.getMastershipTerm(deviceId);
754 if (myId.equals(term.master())) {
755 master = myId;
756 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700757 }
758
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800759 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800760 log.debug("{} has control of {}, forwarding remove request",
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800761 master, deviceId);
762
763 ClusterMessage message = new ClusterMessage(
764 myId,
765 DEVICE_REMOVE_REQ,
766 SERIALIZER.encode(deviceId));
767
768 try {
769 clusterCommunicator.unicast(message, master);
770 } catch (IOException e) {
771 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
772 }
773
774 // event will be triggered after master processes it.
775 return null;
776 }
777
778 // I have control..
779
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700780 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700781 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700782 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800783 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700784 deviceId);
785 try {
786 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
787 } catch (IOException e) {
788 log.error("Failed to notify peers of a device removed topology event for deviceId: {}",
789 deviceId);
790 }
791 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800792 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800793 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800794 mastershipService.relinquishMastership(deviceId);
795 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700796 return event;
797 }
798
799 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
800 Timestamp timestamp) {
801
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700802 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700803 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700804 // accept removal request if given timestamp is newer than
805 // the latest Timestamp from Primary provider
806 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
807 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
808 if (timestamp.compareTo(lastTimestamp) <= 0) {
809 // outdated event ignore
810 return null;
811 }
812 removalRequest.put(deviceId, timestamp);
813
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700814 Device device = devices.remove(deviceId);
815 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700816 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
817 if (ports != null) {
818 ports.clear();
819 }
820 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700821 descs.clear();
822 return device == null ? null :
823 new DeviceEvent(DEVICE_REMOVED, device, null);
824 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700825 }
826
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700827 /**
828 * Checks if given timestamp is superseded by removal request
829 * with more recent timestamp.
830 *
831 * @param deviceId identifier of a device
832 * @param timestampToCheck timestamp of an event to check
833 * @return true if device is already removed
834 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700835 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
836 Timestamp removalTimestamp = removalRequest.get(deviceId);
837 if (removalTimestamp != null &&
838 removalTimestamp.compareTo(timestampToCheck) >= 0) {
839 // removalRequest is more recent
840 return true;
841 }
842 return false;
843 }
844
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700845 /**
846 * Returns a Device, merging description given from multiple Providers.
847 *
848 * @param deviceId device identifier
849 * @param providerDescs Collection of Descriptions from multiple providers
850 * @return Device instance
851 */
852 private Device composeDevice(DeviceId deviceId,
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700853 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700854
Thomas Vachuska444eda62014-10-28 13:09:42 -0700855 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700856
857 ProviderId primary = pickPrimaryPID(providerDescs);
858
859 DeviceDescriptions desc = providerDescs.get(primary);
860
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700861 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700862 Type type = base.type();
863 String manufacturer = base.manufacturer();
864 String hwVersion = base.hwVersion();
865 String swVersion = base.swVersion();
866 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700867 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700868 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
869 annotations = merge(annotations, base.annotations());
870
871 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
872 if (e.getKey().equals(primary)) {
873 continue;
874 }
875 // TODO: should keep track of Description timestamp
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700876 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700877 // Currently assuming there will never be a key conflict between
878 // providers
879
880 // annotation merging. not so efficient, should revisit later
881 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
882 }
883
884 return new DefaultDevice(primary, deviceId , type, manufacturer,
alshabib7911a052014-10-16 17:49:37 -0700885 hwVersion, swVersion, serialNumber,
886 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700887 }
888
889 /**
890 * Returns a Port, merging description given from multiple Providers.
891 *
892 * @param device device the port is on
893 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700894 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700895 * @return Port instance
896 */
897 private Port composePort(Device device, PortNumber number,
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700898 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700899
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700900 ProviderId primary = pickPrimaryPID(descsMap);
901 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700902 // if no primary, assume not enabled
903 // TODO: revisit this default port enabled/disabled behavior
904 boolean isEnabled = false;
905 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
906
907 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
908 if (portDesc != null) {
909 isEnabled = portDesc.value().isEnabled();
910 annotations = merge(annotations, portDesc.value().annotations());
911 }
912
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700913 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700914 if (e.getKey().equals(primary)) {
915 continue;
916 }
917 // TODO: should keep track of Description timestamp
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700918 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700919 // Currently assuming there will never be a key conflict between
920 // providers
921
922 // annotation merging. not so efficient, should revisit later
923 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
924 if (otherPortDesc != null) {
925 annotations = merge(annotations, otherPortDesc.value().annotations());
926 }
927 }
928
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700929 return portDesc == null ?
930 new DefaultPort(device, number, false, annotations) :
931 new DefaultPort(device, number, isEnabled, portDesc.value().type(),
932 portDesc.value().portSpeed(), annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700933 }
934
935 /**
936 * @return primary ProviderID, or randomly chosen one if none exists
937 */
938 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700939 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700940 ProviderId fallBackPrimary = null;
941 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
942 if (!e.getKey().isAncillary()) {
943 return e.getKey();
944 } else if (fallBackPrimary == null) {
945 // pick randomly as a fallback in case there is no primary
946 fallBackPrimary = e.getKey();
947 }
948 }
949 return fallBackPrimary;
950 }
951
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700952 private DeviceDescriptions getPrimaryDescriptions(
953 Map<ProviderId, DeviceDescriptions> providerDescs) {
954 ProviderId pid = pickPrimaryPID(providerDescs);
955 return providerDescs.get(pid);
956 }
957
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700958 // TODO: should we be throwing exception?
959 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
960 ClusterMessage message = new ClusterMessage(
961 clusterService.getLocalNode().id(),
962 subject,
963 SERIALIZER.encode(event));
964 clusterCommunicator.unicast(message, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700965 }
966
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700967 // TODO: should we be throwing exception?
968 private void broadcastMessage(MessageSubject subject, Object event) throws IOException {
969 ClusterMessage message = new ClusterMessage(
970 clusterService.getLocalNode().id(),
971 subject,
972 SERIALIZER.encode(event));
973 clusterCommunicator.broadcast(message);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700974 }
Madan Jampani47c93732014-10-06 20:46:08 -0700975
976 private void notifyPeers(InternalDeviceEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700977 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -0700978 }
979
Madan Jampani25322532014-10-08 11:20:38 -0700980 private void notifyPeers(InternalDeviceOfflineEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700981 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -0700982 }
983
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700984 private void notifyPeers(InternalDeviceRemovedEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700985 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700986 }
987
Madan Jampani47c93732014-10-06 20:46:08 -0700988 private void notifyPeers(InternalPortEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700989 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -0700990 }
991
992 private void notifyPeers(InternalPortStatusEvent event) throws IOException {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700993 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
994 }
995
996 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
997 try {
998 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
999 } catch (IOException e) {
1000 log.error("Failed to send" + event + " to " + recipient, e);
1001 }
1002 }
1003
1004 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1005 try {
1006 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1007 } catch (IOException e) {
1008 log.error("Failed to send" + event + " to " + recipient, e);
1009 }
1010 }
1011
1012 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1013 try {
1014 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1015 } catch (IOException e) {
1016 log.error("Failed to send" + event + " to " + recipient, e);
1017 }
1018 }
1019
1020 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1021 try {
1022 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1023 } catch (IOException e) {
1024 log.error("Failed to send" + event + " to " + recipient, e);
1025 }
1026 }
1027
1028 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1029 try {
1030 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1031 } catch (IOException e) {
1032 log.error("Failed to send" + event + " to " + recipient, e);
1033 }
1034 }
1035
1036 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1037 final NodeId self = clusterService.getLocalNode().id();
1038
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001039 final int numDevices = deviceDescs.size();
1040 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1041 final int portsPerDevice = 8; // random factor to minimize reallocation
1042 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1043 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001044
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001045 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001046
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001047 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001048 synchronized (devDescs) {
1049
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001050 // send device offline timestamp
1051 Timestamp lOffline = this.offline.get(deviceId);
1052 if (lOffline != null) {
1053 adOffline.put(deviceId, lOffline);
1054 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001055
1056 for (Entry<ProviderId, DeviceDescriptions>
1057 prov : devDescs.entrySet()) {
1058
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001059 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001060 final ProviderId provId = prov.getKey();
1061 final DeviceDescriptions descs = prov.getValue();
1062
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001063 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001064 descs.getDeviceDesc().timestamp());
1065
1066 for (Entry<PortNumber, Timestamped<PortDescription>>
1067 portDesc : descs.getPortDescs().entrySet()) {
1068
1069 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001070 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001071 portDesc.getValue().timestamp());
1072 }
1073 }
1074 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001075 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001076
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001077 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001078 }
1079
1080 /**
1081 * Responds to anti-entropy advertisement message.
1082 * <P>
1083 * Notify sender about out-dated information using regular replication message.
1084 * Send back advertisement to sender if not in sync.
1085 *
1086 * @param advertisement to respond to
1087 */
1088 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1089
1090 final NodeId sender = advertisement.sender();
1091
1092 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1093 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1094 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1095
1096 // Fragments to request
1097 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1098 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1099
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001100 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001101 final DeviceId deviceId = de.getKey();
1102 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1103
1104 synchronized (lDevice) {
1105 // latestTimestamp across provider
1106 // Note: can be null initially
1107 Timestamp localLatest = offline.get(deviceId);
1108
1109 // handle device Ads
1110 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1111 final ProviderId provId = prov.getKey();
1112 final DeviceDescriptions lDeviceDescs = prov.getValue();
1113
1114 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1115
1116
1117 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1118 Timestamp advDevTimestamp = devAds.get(devFragId);
1119
1120 if (advDevTimestamp == null || lProvDevice.isNewer(advDevTimestamp)) {
1121 // remote does not have it or outdated, suggest
1122 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1123 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1124 // local is outdated, request
1125 reqDevices.add(devFragId);
1126 }
1127
1128 // handle port Ads
1129 for (Entry<PortNumber, Timestamped<PortDescription>>
1130 pe : lDeviceDescs.getPortDescs().entrySet()) {
1131
1132 final PortNumber num = pe.getKey();
1133 final Timestamped<PortDescription> lPort = pe.getValue();
1134
1135 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1136
1137 Timestamp advPortTimestamp = portAds.get(portFragId);
Yuta HIGUCHIec76bfe2014-10-09 20:17:07 -07001138 if (advPortTimestamp == null || lPort.isNewer(advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001139 // remote does not have it or outdated, suggest
1140 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1141 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1142 // local is outdated, request
1143 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1144 reqPorts.add(portFragId);
1145 }
1146
1147 // remove port Ad already processed
1148 portAds.remove(portFragId);
1149 } // end local port loop
1150
1151 // remove device Ad already processed
1152 devAds.remove(devFragId);
1153
1154 // find latest and update
1155 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1156 if (localLatest == null ||
1157 providerLatest.compareTo(localLatest) > 0) {
1158 localLatest = providerLatest;
1159 }
1160 } // end local provider loop
1161
1162 // checking if remote timestamp is more recent.
1163 Timestamp rOffline = offlineAds.get(deviceId);
1164 if (rOffline != null &&
1165 rOffline.compareTo(localLatest) > 0) {
1166 // remote offline timestamp suggests that the
1167 // device is off-line
1168 markOfflineInternal(deviceId, rOffline);
1169 }
1170
1171 Timestamp lOffline = offline.get(deviceId);
1172 if (lOffline != null && rOffline == null) {
1173 // locally offline, but remote is online, suggest offline
1174 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1175 }
1176
1177 // remove device offline Ad already processed
1178 offlineAds.remove(deviceId);
1179 } // end local device loop
1180 } // device lock
1181
1182 // If there is any Ads left, request them
1183 log.trace("Ads left {}, {}", devAds, portAds);
1184 reqDevices.addAll(devAds.keySet());
1185 reqPorts.addAll(portAds.keySet());
1186
1187 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1188 log.trace("Nothing to request to remote peer {}", sender);
1189 return;
1190 }
1191
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001192 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001193
1194 // 2-way Anti-Entropy for now
1195 try {
1196 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1197 } catch (IOException e) {
1198 log.error("Failed to send response advertisement to " + sender, e);
1199 }
1200
1201// Sketch of 3-way Anti-Entropy
1202// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1203// ClusterMessage message = new ClusterMessage(
1204// clusterService.getLocalNode().id(),
1205// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1206// SERIALIZER.encode(request));
1207//
1208// try {
1209// clusterCommunicator.unicast(message, advertisement.sender());
1210// } catch (IOException e) {
1211// log.error("Failed to send advertisement reply to "
1212// + advertisement.sender(), e);
1213// }
Madan Jampani47c93732014-10-06 20:46:08 -07001214 }
1215
Madan Jampani255a58b2014-10-09 12:08:20 -07001216 private void notifyDelegateIfNotNull(DeviceEvent event) {
1217 if (event != null) {
1218 notifyDelegate(event);
1219 }
1220 }
1221
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001222 private final class SendAdvertisementTask implements Runnable {
1223
1224 @Override
1225 public void run() {
1226 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001227 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001228 return;
1229 }
1230
1231 try {
1232 final NodeId self = clusterService.getLocalNode().id();
1233 Set<ControllerNode> nodes = clusterService.getNodes();
1234
1235 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1236 .transform(toNodeId())
1237 .toList();
1238
1239 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001240 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001241 return;
1242 }
1243
1244 NodeId peer;
1245 do {
1246 int idx = RandomUtils.nextInt(0, nodeIds.size());
1247 peer = nodeIds.get(idx);
1248 } while (peer.equals(self));
1249
1250 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1251
1252 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001253 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001254 return;
1255 }
1256
1257 try {
1258 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1259 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001260 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001261 return;
1262 }
1263 } catch (Exception e) {
1264 // catch all Exception to avoid Scheduled task being suppressed.
1265 log.error("Exception thrown while sending advertisement", e);
1266 }
1267 }
1268 }
1269
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001270 private final class InternalDeviceEventListener
1271 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001272 @Override
1273 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001274
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001275 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001276 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001277
Madan Jampani47c93732014-10-06 20:46:08 -07001278 ProviderId providerId = event.providerId();
1279 DeviceId deviceId = event.deviceId();
1280 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001281
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001282 executor.submit(new Runnable() {
1283
1284 @Override
1285 public void run() {
1286 try {
1287 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1288 } catch (Exception e) {
1289 log.warn("Exception thrown handling device update", e);
1290 }
1291 }
1292 });
Madan Jampani47c93732014-10-06 20:46:08 -07001293 }
1294 }
1295
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001296 private final class InternalDeviceOfflineEventListener
1297 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001298 @Override
1299 public void handle(ClusterMessage message) {
1300
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001301 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001302 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001303
1304 DeviceId deviceId = event.deviceId();
1305 Timestamp timestamp = event.timestamp();
1306
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001307 executor.submit(new Runnable() {
1308
1309 @Override
1310 public void run() {
1311 try {
1312 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1313 } catch (Exception e) {
1314 log.warn("Exception thrown handling device offline", e);
1315 }
1316 }
1317 });
Madan Jampani25322532014-10-08 11:20:38 -07001318 }
1319 }
1320
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001321 private final class InternalRemoveRequestListener
1322 implements ClusterMessageHandler {
1323 @Override
1324 public void handle(ClusterMessage message) {
1325 log.debug("Received device remove request from peer: {}", message.sender());
1326 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001327
1328 executor.submit(new Runnable() {
1329
1330 @Override
1331 public void run() {
1332 try {
1333 removeDevice(did);
1334 } catch (Exception e) {
1335 log.warn("Exception thrown handling device remove", e);
1336 }
1337 }
1338 });
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001339 }
1340 }
1341
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001342 private final class InternalDeviceRemovedEventListener
1343 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001344 @Override
1345 public void handle(ClusterMessage message) {
1346
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001347 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001348 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001349
1350 DeviceId deviceId = event.deviceId();
1351 Timestamp timestamp = event.timestamp();
1352
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001353 executor.submit(new Runnable() {
1354
1355 @Override
1356 public void run() {
1357 try {
1358 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1359 } catch (Exception e) {
1360 log.warn("Exception thrown handling device removed", e);
1361 }
1362 }
1363 });
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001364 }
1365 }
1366
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001367 private final class InternalPortEventListener
1368 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001369 @Override
1370 public void handle(ClusterMessage message) {
1371
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001372 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001373 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001374
1375 ProviderId providerId = event.providerId();
1376 DeviceId deviceId = event.deviceId();
1377 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1378
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001379 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001380 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001381 // Note: dropped information will be recovered by anti-entropy
1382 return;
1383 }
1384
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001385 executor.submit(new Runnable() {
1386
1387 @Override
1388 public void run() {
1389 try {
1390 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1391 } catch (Exception e) {
1392 log.warn("Exception thrown handling port update", e);
1393 }
1394 }
1395 });
Madan Jampani47c93732014-10-06 20:46:08 -07001396 }
1397 }
1398
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001399 private final class InternalPortStatusEventListener
1400 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001401 @Override
1402 public void handle(ClusterMessage message) {
1403
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001404 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001405 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001406
1407 ProviderId providerId = event.providerId();
1408 DeviceId deviceId = event.deviceId();
1409 Timestamped<PortDescription> portDescription = event.portDescription();
1410
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001411 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001412 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001413 // Note: dropped information will be recovered by anti-entropy
1414 return;
1415 }
1416
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001417 executor.submit(new Runnable() {
1418
1419 @Override
1420 public void run() {
1421 try {
1422 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1423 } catch (Exception e) {
1424 log.warn("Exception thrown handling port update", e);
1425 }
1426 }
1427 });
Madan Jampani47c93732014-10-06 20:46:08 -07001428 }
1429 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001430
1431 private final class InternalDeviceAdvertisementListener
1432 implements ClusterMessageHandler {
1433
1434 @Override
1435 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001436 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001437 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Yuta HIGUCHI06586272014-11-25 14:27:03 -08001438 backgroundExecutor.submit(new Runnable() {
1439
1440 @Override
1441 public void run() {
1442 try {
1443 handleAdvertisement(advertisement);
1444 } catch (Exception e) {
1445 log.warn("Exception thrown handling Device advertisements.", e);
1446 }
1447 }
1448 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001449 }
1450 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001451}