blob: eade6e04692de428a0c1512b0eb95ce57117a887 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2014-present Open Networking Laboratory
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07003 *
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 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.store.device.impl;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070017
Jonathan Hart46ab5cc2016-09-15 15:42:39 -070018import com.google.common.collect.FluentIterable;
19import com.google.common.collect.ImmutableList;
20import com.google.common.collect.Maps;
21import com.google.common.collect.Sets;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070022import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070023import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
26import org.apache.felix.scr.annotations.Reference;
27import org.apache.felix.scr.annotations.ReferenceCardinality;
28import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080029import org.onlab.packet.ChassisId;
30import org.onlab.util.KryoNamespace;
Brian O'Connorabafb502014-12-02 22:26:20 -080031import org.onosproject.cluster.ClusterService;
32import org.onosproject.cluster.ControllerNode;
33import org.onosproject.cluster.NodeId;
34import org.onosproject.mastership.MastershipService;
35import org.onosproject.mastership.MastershipTerm;
36import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070037import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080038import org.onosproject.net.AnnotationsUtil;
39import org.onosproject.net.DefaultAnnotations;
40import org.onosproject.net.DefaultDevice;
41import org.onosproject.net.DefaultPort;
42import org.onosproject.net.Device;
43import org.onosproject.net.Device.Type;
44import org.onosproject.net.DeviceId;
45import org.onosproject.net.MastershipRole;
46import org.onosproject.net.Port;
47import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070048import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080049import org.onosproject.net.device.DeviceClockService;
50import org.onosproject.net.device.DeviceDescription;
51import org.onosproject.net.device.DeviceEvent;
52import org.onosproject.net.device.DeviceStore;
53import org.onosproject.net.device.DeviceStoreDelegate;
54import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070055import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080056import org.onosproject.net.provider.ProviderId;
57import org.onosproject.store.AbstractStore;
58import org.onosproject.store.Timestamp;
59import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
Brian O'Connorabafb502014-12-02 22:26:20 -080060import org.onosproject.store.cluster.messaging.MessageSubject;
61import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070062import org.onosproject.store.serializers.KryoNamespaces;
HIGUCHI Yutae7290652016-05-18 11:29:01 -070063import org.onosproject.store.serializers.StoreSerializer;
Brian O'Connor6de2e202015-05-21 14:30:41 -070064import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070065import org.onosproject.store.service.EventuallyConsistentMap;
66import org.onosproject.store.service.EventuallyConsistentMapEvent;
67import org.onosproject.store.service.EventuallyConsistentMapListener;
68import org.onosproject.store.service.MultiValuedTimestamp;
69import org.onosproject.store.service.StorageService;
70import org.onosproject.store.service.WallClockTimestamp;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070071import org.slf4j.Logger;
72
Jonathan Hart46ab5cc2016-09-15 15:42:39 -070073import java.io.IOException;
74import java.util.ArrayList;
75import java.util.Collection;
76import java.util.Collections;
77import java.util.HashMap;
78import java.util.HashSet;
79import java.util.Iterator;
80import java.util.List;
81import java.util.Map;
82import java.util.Map.Entry;
83import java.util.Objects;
84import java.util.Optional;
85import java.util.Set;
86import java.util.concurrent.ConcurrentHashMap;
87import java.util.concurrent.ConcurrentMap;
88import java.util.concurrent.ExecutorService;
89import java.util.concurrent.ScheduledExecutorService;
90import java.util.concurrent.TimeUnit;
91import java.util.function.Consumer;
92import java.util.stream.Stream;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070093
94import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070095import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070096import static com.google.common.base.Verify.verify;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -080097import static java.util.concurrent.Executors.newCachedThreadPool;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080098import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080099import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800100import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800101import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
102import static org.onosproject.net.DefaultAnnotations.merge;
Ray Milkey9ef22232016-07-14 12:42:37 -0700103import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED;
104import static org.onosproject.net.device.DeviceEvent.Type.PORT_ADDED;
105import static org.onosproject.net.device.DeviceEvent.Type.PORT_REMOVED;
106import static org.onosproject.net.device.DeviceEvent.Type.PORT_STATS_UPDATED;
107import static org.onosproject.net.device.DeviceEvent.Type.PORT_UPDATED;
108import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE;
109import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_INJECTED;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700110import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE;
111import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVED;
Ray Milkey9ef22232016-07-14 12:42:37 -0700112import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700113import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_UPDATE;
Ray Milkey9ef22232016-07-14 12:42:37 -0700114import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_INJECTED;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700115import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE;
116import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_UPDATE;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700117import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800118import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700119
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700120/**
121 * Manages inventory of infrastructure devices using gossip protocol to distribute
122 * information.
123 */
124@Component(immediate = true)
125@Service
126public class GossipDeviceStore
127 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
128 implements DeviceStore {
129
130 private final Logger log = getLogger(getClass());
131
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700132 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800133 // Timeout in milliseconds to process device or ports on remote master node
134 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700135
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700136 // innerMap is used to lock a Device, thus instance should never be replaced.
137 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700138 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700139 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700140
141 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700142 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
143 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700144
145 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200146 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700147 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
148 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700149
150 // to be updated under Device lock
151 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
152 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700153
154 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700155 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700156
157 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700158 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700159
Madan Jampani47c93732014-10-06 20:46:08 -0700160 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700161 protected StorageService storageService;
162
163 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700164 protected ClusterCommunicationService clusterCommunicator;
165
Madan Jampani53e44e62014-10-07 12:39:51 -0700166 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
167 protected ClusterService clusterService;
168
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700169 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
170 protected MastershipService mastershipService;
171
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800172 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
173 protected MastershipTermService termService;
174
175
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700176 protected static final StoreSerializer SERIALIZER = StoreSerializer.using(KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800177 .register(DistributedStoreSerializers.STORE_COMMON)
178 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
179 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
180 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700181 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800182 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
183 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700184 .register(DeviceAntiEntropyAdvertisement.class)
185 .register(DeviceFragmentId.class)
186 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800187 .register(DeviceInjectedEvent.class)
188 .register(PortInjectedEvent.class)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700189 .build("GossipDevice"));
Madan Jampani53e44e62014-10-07 12:39:51 -0700190
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800191 private ExecutorService executor;
192
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800193 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700194
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800195 // TODO make these anti-entropy parameters configurable
196 private long initialDelaySec = 5;
197 private long periodSec = 5;
198
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700199 @Activate
200 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800201 executor = newCachedThreadPool(groupedThreads("onos/device", "fg-%d", log));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800202
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800203 backgroundExecutor =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800204 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d", log)));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700205
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700206 addSubscriber(DEVICE_UPDATE, this::handleDeviceEvent);
207 addSubscriber(DEVICE_OFFLINE, this::handleDeviceOfflineEvent);
208 addSubscriber(DEVICE_REMOVE_REQ, this::handleRemoveRequest);
209 addSubscriber(DEVICE_REMOVED, this::handleDeviceRemovedEvent);
210 addSubscriber(PORT_UPDATE, this::handlePortEvent);
211 addSubscriber(PORT_STATUS_UPDATE, this::handlePortStatusEvent);
212 addSubscriber(DEVICE_ADVERTISE, this::handleDeviceAdvertisement);
213 addSubscriber(DEVICE_INJECTED, this::handleDeviceInjectedEvent);
214 addSubscriber(PORT_INJECTED, this::handlePortInjectedEvent);
Madan Jampani2af244a2015-02-22 13:12:01 -0800215
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700216 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800217 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700218 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700219
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700220 // Create a distributed map for port stats.
221 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
222 .register(KryoNamespaces.API)
HIGUCHI Yuta03666a32016-05-18 11:49:09 -0700223 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
224 .register(MultiValuedTimestamp.class);
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700225
226 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
227 .withName("port-stats")
228 .withSerializer(deviceDataSerializer)
229 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700230 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700231 .withTombstonesDisabled()
232 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200233 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
234 eventuallyConsistentMapBuilder()
235 .withName("port-stats-delta")
236 .withSerializer(deviceDataSerializer)
237 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
238 .withTimestampProvider((k, v) -> new WallClockTimestamp())
239 .withTombstonesDisabled()
240 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700241 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700242 log.info("Started");
243 }
244
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700245 private <M> void addSubscriber(MessageSubject subject, Consumer<M> handler) {
246 clusterCommunicator.addSubscriber(subject, SERIALIZER::decode, handler, executor);
247 }
248
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700249 @Deactivate
250 public void deactivate() {
Frank Wange0eb5ce2016-07-01 18:21:25 +0800251 devicePortStats.removeListener(portStatsListener);
Madan Jampani632f16b2015-08-11 12:42:59 -0700252 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200253 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800254 executor.shutdownNow();
255
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800256 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700257 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800258 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700259 log.error("Timeout during executor shutdown");
260 }
261 } catch (InterruptedException e) {
262 log.error("Error during executor shutdown", e);
263 }
264
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700265 deviceDescs.clear();
266 devices.clear();
267 devicePorts.clear();
268 availableDevices.clear();
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700269 clusterCommunicator.removeSubscriber(DEVICE_UPDATE);
270 clusterCommunicator.removeSubscriber(DEVICE_OFFLINE);
271 clusterCommunicator.removeSubscriber(DEVICE_REMOVE_REQ);
272 clusterCommunicator.removeSubscriber(DEVICE_REMOVED);
273 clusterCommunicator.removeSubscriber(PORT_UPDATE);
274 clusterCommunicator.removeSubscriber(PORT_STATUS_UPDATE);
275 clusterCommunicator.removeSubscriber(DEVICE_ADVERTISE);
276 clusterCommunicator.removeSubscriber(DEVICE_INJECTED);
277 clusterCommunicator.removeSubscriber(PORT_INJECTED);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700278 log.info("Stopped");
279 }
280
281 @Override
282 public int getDeviceCount() {
283 return devices.size();
284 }
285
286 @Override
287 public Iterable<Device> getDevices() {
288 return Collections.unmodifiableCollection(devices.values());
289 }
290
291 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800292 public Iterable<Device> getAvailableDevices() {
293 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700294 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800295 }
296
297 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700298 public Device getDevice(DeviceId deviceId) {
299 return devices.get(deviceId);
300 }
301
302 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700303 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700304 DeviceId deviceId,
305 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800306 NodeId localNode = clusterService.getLocalNode().id();
307 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
308
309 // Process device update only if we're the master,
310 // otherwise signal the actual master.
311 DeviceEvent deviceEvent = null;
312 if (localNode.equals(deviceNode)) {
313
314 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
315 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
316 final Timestamped<DeviceDescription> mergedDesc;
317 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
318
319 synchronized (device) {
320 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
321 mergedDesc = device.get(providerId).getDeviceDesc();
322 }
323
324 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700325 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
helenyrwufd296b62016-06-22 17:43:02 -0700326 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800327 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
328 }
329
330 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800331 // Only forward for ConfigProvider
332 // Forwarding was added as a workaround for ONOS-490
Jon Halla3fcf672017-03-28 16:53:22 -0700333 if (!"cfg".equals(providerId.scheme())) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800334 return null;
335 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800336 // FIXME Temporary hack for NPE (ONOS-1171).
337 // Proper fix is to implement forwarding to master on ConfigProvider
338 // redo ONOS-490
339 if (deviceNode == null) {
340 // silently ignore
341 return null;
342 }
343
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800344
345 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
346 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800347
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800348 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700349 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800350 /* error log:
351 log.warn("Failed to process injected device id: {} desc: {} " +
352 "(cluster messaging failed: {})",
353 deviceId, deviceDescription, e);
354 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700355 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800356
357 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700358 }
359
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700360 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700361 DeviceId deviceId,
362 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700363
364 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800365 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700366 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700367
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800368 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700369 // locking per device
370
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700371 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
372 log.debug("Ignoring outdated event: {}", deltaDesc);
373 return null;
374 }
375
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800376 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700377
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700378 final Device oldDevice = devices.get(deviceId);
379 final Device newDevice;
380
381 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700382 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700383 // on new device or valid update
384 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800385 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700386 } else {
387 // outdated event, ignored.
388 return null;
389 }
390 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700391 // REGISTER
392 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700393 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700394 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700395 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700396 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700397 } else {
398 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700399 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
400 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700401 }
402 }
403 }
404
405 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700406 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700407 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700408 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700409
410 // update composed device cache
411 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
412 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700413 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
414 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700415
416 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700417 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700418 }
419
420 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
421 }
422
423 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700424 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700425 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700426 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700427 Device newDevice, Timestamp newTimestamp,
428 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700429 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700430 boolean propertiesChanged =
431 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700432 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
433 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700434 boolean annotationsChanged =
435 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700436
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700437 // Primary providers can respond to all changes, but ancillary ones
438 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800439 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700440 if ((providerId.isAncillary() && annotationsChanged) ||
441 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700442 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
443 if (!replaced) {
444 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700445 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800446 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700447 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700448
alshabibdc5d8bd2015-11-02 15:41:29 -0800449 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700450 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800451
helenyrwufd296b62016-06-22 17:43:02 -0700452 if (!providerId.isAncillary() && forceAvailable) {
alshabibdc5d8bd2015-11-02 15:41:29 -0800453 boolean wasOnline = availableDevices.contains(newDevice.id());
454 markOnline(newDevice.id(), newTimestamp);
455 if (!wasOnline) {
456 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
457 }
458 }
459 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700460 }
461
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700462 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700463 // update composed device cache
464 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
465 verify(oldDevice == null,
466 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
467 providerId, oldDevice, newDevice);
468
469 if (!providerId.isAncillary()) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700470 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700471 }
472
473 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
474 }
475
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700476 @Override
477 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman5b78dc82017-04-19 07:55:48 -0700478 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
479 }
480
481 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700482 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700483 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700484 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700485 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800486 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700487 }
488 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700489 }
490
491 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700492 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700493 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700494
495 // locking device
496 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700497 // accept off-line if given timestamp is newer than
498 // the latest Timestamp from Primary provider
499 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
Thomas Vachuska4bd10b92016-12-15 10:13:38 -0800500 if (primDescs == null) {
501 return null;
502 }
503
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700504 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
505 if (timestamp.compareTo(lastTimestamp) <= 0) {
506 // outdated event ignore
507 return null;
508 }
509
510 offline.put(deviceId, timestamp);
511
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700512 Device device = devices.get(deviceId);
513 if (device == null) {
514 return null;
515 }
516 boolean removed = availableDevices.remove(deviceId);
517 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700518 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700519 }
520 return null;
521 }
522 }
523
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700524 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700525 public boolean markOnline(DeviceId deviceId) {
526 if (devices.containsKey(deviceId)) {
527 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
528 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
529 synchronized (deviceLock) {
530 if (markOnline(deviceId, timestamp)) {
531 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
532 return true;
533 } else {
534 return false;
535 }
536 }
537 }
538 log.warn("Device {} does not exist in store", deviceId);
539 return false;
540
541 }
542
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700543 /**
544 * Marks the device as available if the given timestamp is not outdated,
545 * compared to the time the device has been marked offline.
546 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700547 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700548 * @param timestamp of the event triggering this change.
549 * @return true if availability change request was accepted and changed the state
550 */
551 // Guarded by deviceDescs value (=Device lock)
552 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
553 // accept on-line if given timestamp is newer than
554 // the latest offline request Timestamp
555 Timestamp offlineTimestamp = offline.get(deviceId);
556 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700557 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700558
559 offline.remove(deviceId);
560 return availableDevices.add(deviceId);
561 }
562 return false;
563 }
564
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700565 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700566 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700567 DeviceId deviceId,
568 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700569
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800570 NodeId localNode = clusterService.getLocalNode().id();
571 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
572 // since it will trigger distributed store read.
573 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
574 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
575 // If we don't care much about topology performance, then it might be OK.
576 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700577
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800578 // Process port update only if we're the master of the device,
579 // otherwise signal the actual master.
580 List<DeviceEvent> deviceEvents = null;
581 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700582
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800583 final Timestamp newTimestamp;
584 try {
585 newTimestamp = deviceClockService.getTimestamp(deviceId);
586 } catch (IllegalStateException e) {
587 log.info("Timestamp was not available for device {}", deviceId);
588 log.debug(" discarding {}", portDescriptions);
589 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700590
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800591 // Possible situation:
592 // Device connected and became master for short period of time,
593 // but lost mastership before this instance had the chance to
594 // retrieve term information.
595
596 // Information dropped here is expected to be recoverable by
597 // device probing after mastership change
598
599 return Collections.emptyList();
600 }
601 log.debug("timestamp for {} {}", deviceId, newTimestamp);
602
603 final Timestamped<List<PortDescription>> timestampedInput
604 = new Timestamped<>(portDescriptions, newTimestamp);
605 final Timestamped<List<PortDescription>> merged;
606
607 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
608
609 synchronized (device) {
610 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
611 final DeviceDescriptions descs = device.get(providerId);
612 List<PortDescription> mergedList =
613 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700614 .transform(input ->
615 // lookup merged port description
616 descs.getPortDesc(input.portNumber()).value()
617 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700618 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800619 }
620
621 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700622 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700623 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800624 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
625 }
626
627 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800628 // Only forward for ConfigProvider
629 // Forwarding was added as a workaround for ONOS-490
Jon Halla3fcf672017-03-28 16:53:22 -0700630 if (!"cfg".equals(providerId.scheme())) {
HIGUCHI Yuta89461772016-01-26 12:18:10 -0800631 return Collections.emptyList();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800632 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800633 // FIXME Temporary hack for NPE (ONOS-1171).
634 // Proper fix is to implement forwarding to master on ConfigProvider
635 // redo ONOS-490
636 if (deviceNode == null) {
637 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800638 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800639 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800640
641 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800642
643 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700644 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800645 /* error log:
646 log.warn("Failed to process injected ports of device id: {} " +
647 "(cluster messaging failed: {})",
648 deviceId, e);
649 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700650 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700651
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800652 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700653 }
654
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700655 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700656 DeviceId deviceId,
657 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700658
659 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700660 if (device == null) {
661 log.debug("Device is no longer valid: {}", deviceId);
662 return Collections.emptyList();
663 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700664
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700665 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700666 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
667
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700668 List<DeviceEvent> events = new ArrayList<>();
669 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700670
671 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
672 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700673 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700674 }
675
676 DeviceDescriptions descs = descsMap.get(providerId);
677 // every provider must provide DeviceDescription.
678 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700679 "Device description for Device ID %s from Provider %s was not found",
680 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700681
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700682 Map<PortNumber, Port> ports = getPortMap(deviceId);
683
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700684 final Timestamp newTimestamp = portDescriptions.timestamp();
685
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700686 // Add new ports
687 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700688 for (PortDescription portDescription : portDescriptions.value()) {
689 final PortNumber number = portDescription.portNumber();
690 processed.add(number);
691
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700692 final Port oldPort = ports.get(number);
693 final Port newPort;
694
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700695
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700696 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
697 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700698 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700699 // on new port or valid update
700 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700701 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700702 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700703 newPort = composePort(device, number, descsMap);
704 } else {
705 // outdated event, ignored.
706 continue;
707 }
708
709 events.add(oldPort == null ?
710 createPort(device, newPort, ports) :
711 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700712 }
713
714 events.addAll(pruneOldPorts(device, ports, processed));
715 }
716 return FluentIterable.from(events).filter(notNull()).toList();
717 }
718
719 // Creates a new port based on the port description adds it to the map and
720 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700721 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700722 private DeviceEvent createPort(Device device, Port newPort,
723 Map<PortNumber, Port> ports) {
724 ports.put(newPort.number(), newPort);
725 return new DeviceEvent(PORT_ADDED, device, newPort);
726 }
727
728 // Checks if the specified port requires update and if so, it replaces the
729 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700730 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700731 private DeviceEvent updatePort(Device device, Port oldPort,
732 Port newPort,
733 Map<PortNumber, Port> ports) {
Michal Machce774332017-01-25 11:02:55 +0100734
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700735 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700736 oldPort.type() != newPort.type() ||
737 oldPort.portSpeed() != newPort.portSpeed() ||
738 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700739 ports.put(oldPort.number(), newPort);
740 return new DeviceEvent(PORT_UPDATED, device, newPort);
741 }
742 return null;
743 }
744
Michal Machce774332017-01-25 11:02:55 +0100745 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
746
747 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
748 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
749
750 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
751 }
752
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700753 // Prunes the specified list of ports based on which ports are in the
754 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700755 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700756 private List<DeviceEvent> pruneOldPorts(Device device,
757 Map<PortNumber, Port> ports,
758 Set<PortNumber> processed) {
759 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700760 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700761 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700762 Entry<PortNumber, Port> e = iterator.next();
763 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700764 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700765 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700766 iterator.remove();
767 }
768 }
769 return events;
770 }
771
772 // Gets the map of ports for the specified device; if one does not already
773 // exist, it creates and registers a new one.
774 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700775 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700776 }
777
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700778 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700779 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700780 Map<ProviderId, DeviceDescriptions> r;
781 r = deviceDescs.get(deviceId);
782 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700783 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700784 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
785 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
786 if (concurrentlyAdded != null) {
787 r = concurrentlyAdded;
788 }
789 }
790 return r;
791 }
792
793 // Guarded by deviceDescs value (=Device lock)
794 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
795 Map<ProviderId, DeviceDescriptions> device,
796 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700797 synchronized (device) {
798 DeviceDescriptions r = device.get(providerId);
799 if (r == null) {
800 r = new DeviceDescriptions(deltaDesc);
801 device.put(providerId, r);
802 }
803 return r;
804 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700805 }
806
807 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700808 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
809 DeviceId deviceId,
810 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700811 final Timestamp newTimestamp;
812 try {
813 newTimestamp = deviceClockService.getTimestamp(deviceId);
814 } catch (IllegalStateException e) {
815 log.info("Timestamp was not available for device {}", deviceId);
816 log.debug(" discarding {}", portDescription);
817 // Failed to generate timestamp. Ignoring.
818 // See updatePorts comment
819 return null;
820 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700821 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700822 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700823 final DeviceEvent event;
824 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800825 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
826 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700827 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800828 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700829 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700830 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700831 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700832 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700833 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800834 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700835 }
836 return event;
837 }
838
839 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700840 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700841 Device device = devices.get(deviceId);
842 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
843
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700844 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700845 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
846
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700847 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700848
849 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
850 log.debug("Ignoring outdated event: {}", deltaDesc);
851 return null;
852 }
853
854 DeviceDescriptions descs = descsMap.get(providerId);
855 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700856 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700857 "Device description for Device ID %s from Provider %s was not found",
858 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700859
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700860 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
861 final PortNumber number = deltaDesc.value().portNumber();
862 final Port oldPort = ports.get(number);
863 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700864 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Machce774332017-01-25 11:02:55 +0100865 boolean toDelete = false;
866
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700867 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700868 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700869 // on new port or valid update
870 // update description
871 descs.putPortDesc(deltaDesc);
872 newPort = composePort(device, number, descsMap);
Michal Machce774332017-01-25 11:02:55 +0100873 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700874 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700875 // same or outdated event, ignored.
876 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700877 return null;
878 }
879
880 if (oldPort == null) {
881 return createPort(device, newPort, ports);
882 } else {
Michal Machce774332017-01-25 11:02:55 +0100883 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700884 }
885 }
886 }
887
888 @Override
889 public List<Port> getPorts(DeviceId deviceId) {
890 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
891 if (ports == null) {
892 return Collections.emptyList();
893 }
894 return ImmutableList.copyOf(ports.values());
895 }
896
897 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700898 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
899 DeviceId deviceId) {
900 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
901 if (descs == null) {
902 return null;
903 }
904 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
905 final Optional<DeviceDescriptions> devDescs;
906 synchronized (descs) {
907 devDescs = Optional.ofNullable(descs.get(pid));
908 }
909 // DeviceDescriptions is concurrent access-safe
910 return devDescs
911 .map(dd -> dd.getPortDescs().values().stream()
912 .map(Timestamped::value))
913 .orElse(Stream.empty());
914 }
915
916 @Override
sangho538108b2015-04-08 14:29:20 -0700917 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200918 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700919
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200920 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
921 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
922 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
923
924 if (prvStatsMap != null) {
925 for (PortStatistics newStats : newStatsCollection) {
926 PortNumber port = PortNumber.portNumber(newStats.port());
927 PortStatistics prvStats = prvStatsMap.get(port);
928 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
929 PortStatistics deltaStats = builder.build();
930 if (prvStats != null) {
931 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
932 }
933 deltaStatsMap.put(port, deltaStats);
934 newStatsMap.put(port, newStats);
935 }
936 } else {
937 for (PortStatistics newStats : newStatsCollection) {
938 PortNumber port = PortNumber.portNumber(newStats.port());
939 newStatsMap.put(port, newStats);
940 }
sangho538108b2015-04-08 14:29:20 -0700941 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200942 devicePortDeltaStats.put(deviceId, deltaStatsMap);
943 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200944 // DeviceEvent returns null because of InternalPortStatsListener usage
945 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200946 }
947
948 /**
949 * Calculate delta statistics by subtracting previous from new statistics.
950 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700951 * @param deviceId device identifier
952 * @param prvStats previous port statistics
953 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200954 * @return PortStatistics
955 */
956 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
957 // calculate time difference
958 long deltaStatsSec, deltaStatsNano;
959 if (newStats.durationNano() < prvStats.durationNano()) {
960 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
961 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
962 } else {
963 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
964 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
965 }
966 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
967 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
968 .setPort(newStats.port())
969 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
970 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
971 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
972 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
973 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
974 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
975 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
976 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
977 .setDurationSec(deltaStatsSec)
978 .setDurationNano(deltaStatsNano)
979 .build();
980 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700981 }
982
983 @Override
984 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700985 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
986 if (portStats == null) {
987 return Collections.emptyList();
988 }
989 return ImmutableList.copyOf(portStats.values());
990 }
991
992 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530993 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
994 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
995 if (portStatsMap == null) {
996 return null;
997 }
998 PortStatistics portStats = portStatsMap.get(portNumber);
999 return portStats;
1000 }
1001
1002 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001003 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
1004 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
1005 if (portStats == null) {
1006 return Collections.emptyList();
1007 }
1008 return ImmutableList.copyOf(portStats.values());
1009 }
1010
1011 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +05301012 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
1013 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
1014 if (portStatsMap == null) {
1015 return null;
1016 }
1017 PortStatistics portStats = portStatsMap.get(portNumber);
1018 return portStats;
1019 }
1020
1021 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001022 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
1023 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1024 return ports == null ? null : ports.get(portNumber);
1025 }
1026
1027 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -07001028 public PortDescription getPortDescription(ProviderId pid,
1029 DeviceId deviceId,
1030 PortNumber portNumber) {
1031 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1032 if (descs == null) {
1033 return null;
1034 }
1035 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1036 final Optional<DeviceDescriptions> devDescs;
1037 synchronized (descs) {
1038 devDescs = Optional.ofNullable(descs.get(pid));
1039 }
1040 // DeviceDescriptions is concurrent access-safe
1041 return devDescs
1042 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1043 .map(Timestamped::value)
1044 .orElse(null);
1045 }
1046
1047 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001048 public boolean isAvailable(DeviceId deviceId) {
1049 return availableDevices.contains(deviceId);
1050 }
1051
1052 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001053 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001054 final NodeId myId = clusterService.getLocalNode().id();
1055 NodeId master = mastershipService.getMasterFor(deviceId);
1056
1057 // if there exist a master, forward
1058 // if there is no master, try to become one and process
1059
1060 boolean relinquishAtEnd = false;
1061 if (master == null) {
1062 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1063 if (myRole != MastershipRole.NONE) {
1064 relinquishAtEnd = true;
1065 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001066 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001067 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001068 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -07001069 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001070 master = myId;
1071 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001072 }
1073
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001074 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001075 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001076 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001077
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001078 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001079 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001080 /* error log:
1081 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1082 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001083
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001084 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001085 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001086 }
1087
1088 // I have control..
1089
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -07001090 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001091 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001092 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001093 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001094 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001095 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001096 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001097 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001098 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001099 mastershipService.relinquishMastership(deviceId);
1100 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001101 return event;
1102 }
1103
1104 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
1105 Timestamp timestamp) {
1106
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001107 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001108 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001109 // accept removal request if given timestamp is newer than
1110 // the latest Timestamp from Primary provider
1111 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001112 if (primDescs == null) {
1113 return null;
1114 }
1115
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001116 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
1117 if (timestamp.compareTo(lastTimestamp) <= 0) {
1118 // outdated event ignore
1119 return null;
1120 }
1121 removalRequest.put(deviceId, timestamp);
1122
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001123 Device device = devices.remove(deviceId);
1124 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001125 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1126 if (ports != null) {
1127 ports.clear();
1128 }
1129 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001130 descs.clear();
1131 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001132 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001133 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001134 }
1135
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001136 /**
1137 * Checks if given timestamp is superseded by removal request
1138 * with more recent timestamp.
1139 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001140 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001141 * @param timestampToCheck timestamp of an event to check
1142 * @return true if device is already removed
1143 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001144 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1145 Timestamp removalTimestamp = removalRequest.get(deviceId);
1146 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001147 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001148 // removalRequest is more recent
1149 return true;
1150 }
1151 return false;
1152 }
1153
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001154 /**
1155 * Returns a Device, merging description given from multiple Providers.
1156 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001157 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001158 * @param providerDescs Collection of Descriptions from multiple providers
1159 * @return Device instance
1160 */
1161 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001162 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001163
Thomas Vachuska444eda62014-10-28 13:09:42 -07001164 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001165
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001166 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001167
1168 DeviceDescriptions desc = providerDescs.get(primary);
1169
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001170 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001171 Type type = base.type();
1172 String manufacturer = base.manufacturer();
1173 String hwVersion = base.hwVersion();
1174 String swVersion = base.swVersion();
1175 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001176 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001177 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1178 annotations = merge(annotations, base.annotations());
1179
1180 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1181 if (e.getKey().equals(primary)) {
1182 continue;
1183 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001184 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001185 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001186 // Currently assuming there will never be a key conflict between
1187 // providers
1188
1189 // annotation merging. not so efficient, should revisit later
1190 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1191 }
1192
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001193 return new DefaultDevice(primary, deviceId, type, manufacturer,
1194 hwVersion, swVersion, serialNumber,
1195 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001196 }
1197
Marc De Leenheer88194c32015-05-29 22:10:59 -07001198 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1199 PortDescription description, Annotations annotations) {
Marc De Leenheer88194c32015-05-29 22:10:59 -07001200 return new DefaultPort(device, number, isEnabled, description.type(),
1201 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001202 }
1203
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001204 /**
1205 * Returns a Port, merging description given from multiple Providers.
1206 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001207 * @param device device the port is on
1208 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001209 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001210 * @return Port instance
1211 */
1212 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001213 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001214
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001215 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001216 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001217 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001218 boolean isEnabled = false;
1219 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001220 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001221 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1222 if (portDesc != null) {
1223 isEnabled = portDesc.value().isEnabled();
1224 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001225 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001226 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001227 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001228 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001229 if (e.getKey().equals(primary)) {
1230 continue;
1231 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001232 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001233 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001234 // Currently assuming there will never be a key conflict between
1235 // providers
1236
1237 // annotation merging. not so efficient, should revisit later
1238 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1239 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001240 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1241 continue;
1242 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001243 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001244 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001245 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001246 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001247 }
1248 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001249 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001250 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001251 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001252 PortDescription current = portDesc.value();
1253 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001254 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001255 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001256 }
1257
1258 /**
1259 * @return primary ProviderID, or randomly chosen one if none exists
1260 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001261 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001262 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001263 ProviderId fallBackPrimary = null;
1264 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1265 if (!e.getKey().isAncillary()) {
1266 return e.getKey();
1267 } else if (fallBackPrimary == null) {
1268 // pick randomly as a fallback in case there is no primary
1269 fallBackPrimary = e.getKey();
1270 }
1271 }
1272 return fallBackPrimary;
1273 }
1274
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001275 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001276 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001277 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001278 return providerDescs.get(pid);
1279 }
1280
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001281 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001282 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001283 }
1284
Jonathan Hart7d656f42015-01-27 14:07:23 -08001285 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001286 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001287 }
Madan Jampani47c93732014-10-06 20:46:08 -07001288
Jonathan Hart7d656f42015-01-27 14:07:23 -08001289 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001290 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001291 }
1292
Jonathan Hart7d656f42015-01-27 14:07:23 -08001293 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001294 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001295 }
1296
Jonathan Hart7d656f42015-01-27 14:07:23 -08001297 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001298 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001299 }
1300
Jonathan Hart7d656f42015-01-27 14:07:23 -08001301 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001302 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001303 }
1304
Jonathan Hart7d656f42015-01-27 14:07:23 -08001305 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001306 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1307 }
1308
1309 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1310 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001311 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001312 } catch (IOException e) {
1313 log.error("Failed to send" + event + " to " + recipient, e);
1314 }
1315 }
1316
1317 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1318 try {
1319 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1320 } catch (IOException e) {
1321 log.error("Failed to send" + event + " to " + recipient, e);
1322 }
1323 }
1324
1325 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1326 try {
1327 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1328 } catch (IOException e) {
1329 log.error("Failed to send" + event + " to " + recipient, e);
1330 }
1331 }
1332
1333 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1334 try {
1335 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1336 } catch (IOException e) {
1337 log.error("Failed to send" + event + " to " + recipient, e);
1338 }
1339 }
1340
1341 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1342 try {
1343 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1344 } catch (IOException e) {
1345 log.error("Failed to send" + event + " to " + recipient, e);
1346 }
1347 }
1348
1349 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1350 final NodeId self = clusterService.getLocalNode().id();
1351
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001352 final int numDevices = deviceDescs.size();
1353 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1354 final int portsPerDevice = 8; // random factor to minimize reallocation
1355 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1356 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001357
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001358 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001359
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001360 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001361 synchronized (devDescs) {
1362
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001363 // send device offline timestamp
1364 Timestamp lOffline = this.offline.get(deviceId);
1365 if (lOffline != null) {
1366 adOffline.put(deviceId, lOffline);
1367 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001368
1369 for (Entry<ProviderId, DeviceDescriptions>
1370 prov : devDescs.entrySet()) {
1371
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001372 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001373 final ProviderId provId = prov.getKey();
1374 final DeviceDescriptions descs = prov.getValue();
1375
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001376 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001377 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001378
1379 for (Entry<PortNumber, Timestamped<PortDescription>>
1380 portDesc : descs.getPortDescs().entrySet()) {
1381
1382 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001383 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001384 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001385 }
1386 }
1387 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001388 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001389
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001390 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001391 }
1392
1393 /**
1394 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001395 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001396 * Notify sender about out-dated information using regular replication message.
1397 * Send back advertisement to sender if not in sync.
1398 *
1399 * @param advertisement to respond to
1400 */
1401 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1402
1403 final NodeId sender = advertisement.sender();
1404
1405 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1406 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1407 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1408
1409 // Fragments to request
1410 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1411 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1412
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001413 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001414 final DeviceId deviceId = de.getKey();
1415 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1416
1417 synchronized (lDevice) {
1418 // latestTimestamp across provider
1419 // Note: can be null initially
1420 Timestamp localLatest = offline.get(deviceId);
1421
1422 // handle device Ads
1423 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1424 final ProviderId provId = prov.getKey();
1425 final DeviceDescriptions lDeviceDescs = prov.getValue();
1426
1427 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1428
1429
1430 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1431 Timestamp advDevTimestamp = devAds.get(devFragId);
1432
Jonathan Hart403ea932015-02-20 16:23:00 -08001433 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1434 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001435 // remote does not have it or outdated, suggest
1436 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1437 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1438 // local is outdated, request
1439 reqDevices.add(devFragId);
1440 }
1441
1442 // handle port Ads
1443 for (Entry<PortNumber, Timestamped<PortDescription>>
1444 pe : lDeviceDescs.getPortDescs().entrySet()) {
1445
1446 final PortNumber num = pe.getKey();
1447 final Timestamped<PortDescription> lPort = pe.getValue();
1448
1449 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1450
1451 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001452 if (advPortTimestamp == null || lPort.isNewerThan(
1453 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001454 // remote does not have it or outdated, suggest
1455 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1456 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1457 // local is outdated, request
1458 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1459 reqPorts.add(portFragId);
1460 }
1461
1462 // remove port Ad already processed
1463 portAds.remove(portFragId);
1464 } // end local port loop
1465
1466 // remove device Ad already processed
1467 devAds.remove(devFragId);
1468
1469 // find latest and update
1470 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1471 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001472 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001473 localLatest = providerLatest;
1474 }
1475 } // end local provider loop
1476
1477 // checking if remote timestamp is more recent.
1478 Timestamp rOffline = offlineAds.get(deviceId);
1479 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001480 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001481 // remote offline timestamp suggests that the
1482 // device is off-line
1483 markOfflineInternal(deviceId, rOffline);
1484 }
1485
1486 Timestamp lOffline = offline.get(deviceId);
1487 if (lOffline != null && rOffline == null) {
1488 // locally offline, but remote is online, suggest offline
1489 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1490 }
1491
1492 // remove device offline Ad already processed
1493 offlineAds.remove(deviceId);
1494 } // end local device loop
1495 } // device lock
1496
1497 // If there is any Ads left, request them
1498 log.trace("Ads left {}, {}", devAds, portAds);
1499 reqDevices.addAll(devAds.keySet());
1500 reqPorts.addAll(portAds.keySet());
1501
1502 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1503 log.trace("Nothing to request to remote peer {}", sender);
1504 return;
1505 }
1506
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001507 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001508
1509 // 2-way Anti-Entropy for now
1510 try {
1511 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1512 } catch (IOException e) {
1513 log.error("Failed to send response advertisement to " + sender, e);
1514 }
1515
1516// Sketch of 3-way Anti-Entropy
1517// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1518// ClusterMessage message = new ClusterMessage(
1519// clusterService.getLocalNode().id(),
1520// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1521// SERIALIZER.encode(request));
1522//
1523// try {
1524// clusterCommunicator.unicast(message, advertisement.sender());
1525// } catch (IOException e) {
1526// log.error("Failed to send advertisement reply to "
1527// + advertisement.sender(), e);
1528// }
Madan Jampani47c93732014-10-06 20:46:08 -07001529 }
1530
Madan Jampani255a58b2014-10-09 12:08:20 -07001531 private void notifyDelegateIfNotNull(DeviceEvent event) {
1532 if (event != null) {
1533 notifyDelegate(event);
1534 }
1535 }
1536
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001537 private final class SendAdvertisementTask implements Runnable {
1538
1539 @Override
1540 public void run() {
1541 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001542 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001543 return;
1544 }
1545
1546 try {
1547 final NodeId self = clusterService.getLocalNode().id();
1548 Set<ControllerNode> nodes = clusterService.getNodes();
1549
1550 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1551 .transform(toNodeId())
1552 .toList();
1553
1554 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001555 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001556 return;
1557 }
1558
1559 NodeId peer;
1560 do {
1561 int idx = RandomUtils.nextInt(0, nodeIds.size());
1562 peer = nodeIds.get(idx);
1563 } while (peer.equals(self));
1564
1565 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1566
1567 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001568 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001569 return;
1570 }
1571
1572 try {
1573 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1574 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001575 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001576 return;
1577 }
1578 } catch (Exception e) {
1579 // catch all Exception to avoid Scheduled task being suppressed.
1580 log.error("Exception thrown while sending advertisement", e);
1581 }
1582 }
1583 }
1584
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001585 private void handleDeviceEvent(InternalDeviceEvent event) {
1586 ProviderId providerId = event.providerId();
1587 DeviceId deviceId = event.deviceId();
1588 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001589
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001590 try {
1591 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1592 deviceDescription));
1593 } catch (Exception e) {
1594 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001595 }
1596 }
1597
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001598 private void handleDeviceOfflineEvent(InternalDeviceOfflineEvent event) {
1599 DeviceId deviceId = event.deviceId();
1600 Timestamp timestamp = event.timestamp();
Madan Jampani25322532014-10-08 11:20:38 -07001601
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001602 try {
1603 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1604 } catch (Exception e) {
1605 log.warn("Exception thrown handling device offline", e);
Madan Jampani25322532014-10-08 11:20:38 -07001606 }
1607 }
1608
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001609 private void handleRemoveRequest(DeviceId did) {
1610 try {
1611 removeDevice(did);
1612 } catch (Exception e) {
1613 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001614 }
1615 }
1616
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001617 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1618 DeviceId deviceId = event.deviceId();
1619 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001620
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001621 try {
1622 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1623 } catch (Exception e) {
1624 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001625 }
1626 }
1627
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001628 private void handlePortEvent(InternalPortEvent event) {
1629 ProviderId providerId = event.providerId();
1630 DeviceId deviceId = event.deviceId();
1631 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001632
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001633 if (getDevice(deviceId) == null) {
1634 log.debug("{} not found on this node yet, ignoring.", deviceId);
1635 // Note: dropped information will be recovered by anti-entropy
1636 return;
1637 }
Madan Jampani47c93732014-10-06 20:46:08 -07001638
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001639 try {
1640 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1641 } catch (Exception e) {
1642 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001643 }
1644 }
1645
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001646 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1647 ProviderId providerId = event.providerId();
1648 DeviceId deviceId = event.deviceId();
1649 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001650
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001651 if (getDevice(deviceId) == null) {
1652 log.debug("{} not found on this node yet, ignoring.", deviceId);
1653 // Note: dropped information will be recovered by anti-entropy
1654 return;
1655 }
Madan Jampani47c93732014-10-06 20:46:08 -07001656
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001657 try {
1658 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1659 } catch (Exception e) {
1660 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001661 }
1662 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001663
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001664 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1665 try {
1666 handleAdvertisement(advertisement);
1667 } catch (Exception e) {
1668 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001669 }
1670 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001671
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001672 private void handleDeviceInjectedEvent(DeviceInjectedEvent event) {
1673 ProviderId providerId = event.providerId();
1674 DeviceId deviceId = event.deviceId();
1675 DeviceDescription deviceDescription = event.deviceDescription();
1676 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1677 // workaround for ONOS-1208
1678 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1679 return;
1680 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001681
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001682 try {
1683 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1684 } catch (Exception e) {
1685 log.warn("Exception thrown handling device injected event.", e);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001686 }
1687 }
1688
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001689 private void handlePortInjectedEvent(PortInjectedEvent event) {
1690 ProviderId providerId = event.providerId();
1691 DeviceId deviceId = event.deviceId();
1692 List<PortDescription> portDescriptions = event.portDescriptions();
1693 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1694 // workaround for ONOS-1208
1695 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1696 return;
1697 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001698
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001699 try {
1700 updatePorts(providerId, deviceId, portDescriptions);
1701 } catch (Exception e) {
1702 log.warn("Exception thrown handling port injected event.", e);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001703 }
1704 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001705
1706 private class InternalPortStatsListener
1707 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1708 @Override
1709 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1710 if (event.type() == PUT) {
1711 Device device = devices.get(event.key());
1712 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001713 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001714 }
1715 }
1716 }
1717 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001718}