blob: c81d7ab4551ae4378ad208c4ebb67dfa4ece1d4c [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
Ray Milkey9ef22232016-07-14 12:42:37 -070018import java.io.IOException;
19import java.util.ArrayList;
20import java.util.Collection;
21import java.util.Collections;
22import java.util.HashMap;
23import java.util.HashSet;
24import java.util.Iterator;
25import java.util.List;
26import java.util.Map;
27import java.util.Map.Entry;
28import java.util.Objects;
29import java.util.Optional;
30import java.util.Set;
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -070031import java.util.concurrent.ConcurrentHashMap;
Ray Milkey9ef22232016-07-14 12:42:37 -070032import java.util.concurrent.ConcurrentMap;
33import java.util.concurrent.ExecutorService;
34import java.util.concurrent.ScheduledExecutorService;
35import java.util.concurrent.TimeUnit;
36import java.util.stream.Stream;
Dusan Pajin11ff4a82015-08-20 18:03:05 +020037
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070038import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070039import org.apache.felix.scr.annotations.Activate;
40import org.apache.felix.scr.annotations.Component;
41import org.apache.felix.scr.annotations.Deactivate;
42import org.apache.felix.scr.annotations.Reference;
43import org.apache.felix.scr.annotations.ReferenceCardinality;
44import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080045import org.onlab.packet.ChassisId;
46import org.onlab.util.KryoNamespace;
Brian O'Connorabafb502014-12-02 22:26:20 -080047import org.onosproject.cluster.ClusterService;
48import org.onosproject.cluster.ControllerNode;
49import org.onosproject.cluster.NodeId;
50import org.onosproject.mastership.MastershipService;
51import org.onosproject.mastership.MastershipTerm;
52import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070053import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080054import org.onosproject.net.AnnotationsUtil;
55import org.onosproject.net.DefaultAnnotations;
56import org.onosproject.net.DefaultDevice;
57import org.onosproject.net.DefaultPort;
58import org.onosproject.net.Device;
59import org.onosproject.net.Device.Type;
60import org.onosproject.net.DeviceId;
61import org.onosproject.net.MastershipRole;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070062import org.onosproject.net.OchPort;
63import org.onosproject.net.OduCltPort;
64import org.onosproject.net.OmsPort;
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +020065import org.onosproject.net.OtuPort;
Brian O'Connorabafb502014-12-02 22:26:20 -080066import org.onosproject.net.Port;
67import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070068import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080069import org.onosproject.net.device.DeviceClockService;
70import org.onosproject.net.device.DeviceDescription;
71import org.onosproject.net.device.DeviceEvent;
72import org.onosproject.net.device.DeviceStore;
73import org.onosproject.net.device.DeviceStoreDelegate;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070074import org.onosproject.net.device.OchPortDescription;
75import org.onosproject.net.device.OduCltPortDescription;
76import org.onosproject.net.device.OmsPortDescription;
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +020077import org.onosproject.net.device.OtuPortDescription;
Brian O'Connorabafb502014-12-02 22:26:20 -080078import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070079import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080080import org.onosproject.net.provider.ProviderId;
81import org.onosproject.store.AbstractStore;
82import org.onosproject.store.Timestamp;
83import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
84import org.onosproject.store.cluster.messaging.ClusterMessage;
85import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
86import org.onosproject.store.cluster.messaging.MessageSubject;
87import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070088import org.onosproject.store.serializers.KryoNamespaces;
HIGUCHI Yutae7290652016-05-18 11:29:01 -070089import org.onosproject.store.serializers.StoreSerializer;
Brian O'Connor6de2e202015-05-21 14:30:41 -070090import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070091import org.onosproject.store.service.EventuallyConsistentMap;
92import org.onosproject.store.service.EventuallyConsistentMapEvent;
93import org.onosproject.store.service.EventuallyConsistentMapListener;
94import org.onosproject.store.service.MultiValuedTimestamp;
95import org.onosproject.store.service.StorageService;
96import org.onosproject.store.service.WallClockTimestamp;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070097import org.slf4j.Logger;
98
Ray Milkey9ef22232016-07-14 12:42:37 -070099import com.google.common.collect.FluentIterable;
100import com.google.common.collect.ImmutableList;
101import com.google.common.collect.Maps;
102import com.google.common.collect.Sets;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700103
104import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700105import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700106import static com.google.common.base.Verify.verify;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800107import static java.util.concurrent.Executors.newCachedThreadPool;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800108import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800109import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800110import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800111import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
112import static org.onosproject.net.DefaultAnnotations.merge;
Ray Milkey9ef22232016-07-14 12:42:37 -0700113import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED;
114import static org.onosproject.net.device.DeviceEvent.Type.PORT_ADDED;
115import static org.onosproject.net.device.DeviceEvent.Type.PORT_REMOVED;
116import static org.onosproject.net.device.DeviceEvent.Type.PORT_STATS_UPDATED;
117import static org.onosproject.net.device.DeviceEvent.Type.PORT_UPDATED;
118import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE;
119import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_INJECTED;
120import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
121import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_INJECTED;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700122import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800123import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700124
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700125/**
126 * Manages inventory of infrastructure devices using gossip protocol to distribute
127 * information.
128 */
129@Component(immediate = true)
130@Service
131public class GossipDeviceStore
132 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
133 implements DeviceStore {
134
135 private final Logger log = getLogger(getClass());
136
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700137 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800138 // Timeout in milliseconds to process device or ports on remote master node
139 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700140
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700141 // innerMap is used to lock a Device, thus instance should never be replaced.
142 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700143 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700144 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700145
146 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700147 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
148 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700149
150 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200151 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700152 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
153 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700154
155 // to be updated under Device lock
156 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
157 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700158
159 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700160 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700161
162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700163 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700164
Madan Jampani47c93732014-10-06 20:46:08 -0700165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700166 protected StorageService storageService;
167
168 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700169 protected ClusterCommunicationService clusterCommunicator;
170
Madan Jampani53e44e62014-10-07 12:39:51 -0700171 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
172 protected ClusterService clusterService;
173
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700174 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
175 protected MastershipService mastershipService;
176
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800177 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
178 protected MastershipTermService termService;
179
180
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700181 protected static final StoreSerializer SERIALIZER = StoreSerializer.using(KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800182 .register(DistributedStoreSerializers.STORE_COMMON)
183 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
184 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
185 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700186 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800187 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
188 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700189 .register(DeviceAntiEntropyAdvertisement.class)
190 .register(DeviceFragmentId.class)
191 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800192 .register(DeviceInjectedEvent.class)
193 .register(PortInjectedEvent.class)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700194 .build("GossipDevice"));
Madan Jampani53e44e62014-10-07 12:39:51 -0700195
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800196 private ExecutorService executor;
197
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800198 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700199
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800200 // TODO make these anti-entropy parameters configurable
201 private long initialDelaySec = 5;
202 private long periodSec = 5;
203
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700204 @Activate
205 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800206 executor = newCachedThreadPool(groupedThreads("onos/device", "fg-%d", log));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800207
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800208 backgroundExecutor =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800209 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d", log)));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700210
Madan Jampani2af244a2015-02-22 13:12:01 -0800211 clusterCommunicator.addSubscriber(
212 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
213 clusterCommunicator.addSubscriber(
214 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
215 new InternalDeviceOfflineEventListener(),
216 executor);
217 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700218 new InternalRemoveRequestListener(),
219 executor);
Madan Jampani2af244a2015-02-22 13:12:01 -0800220 clusterCommunicator.addSubscriber(
221 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
222 clusterCommunicator.addSubscriber(
223 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
224 clusterCommunicator.addSubscriber(
225 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
226 clusterCommunicator.addSubscriber(
227 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
228 new InternalDeviceAdvertisementListener(),
229 backgroundExecutor);
230 clusterCommunicator.addSubscriber(
231 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
232 clusterCommunicator.addSubscriber(
233 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
234
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700235 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800236 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700237 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700238
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700239 // Create a distributed map for port stats.
240 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
241 .register(KryoNamespaces.API)
HIGUCHI Yuta03666a32016-05-18 11:49:09 -0700242 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
243 .register(MultiValuedTimestamp.class);
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700244
245 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
246 .withName("port-stats")
247 .withSerializer(deviceDataSerializer)
248 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700249 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700250 .withTombstonesDisabled()
251 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200252 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
253 eventuallyConsistentMapBuilder()
254 .withName("port-stats-delta")
255 .withSerializer(deviceDataSerializer)
256 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
257 .withTimestampProvider((k, v) -> new WallClockTimestamp())
258 .withTombstonesDisabled()
259 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700260 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700261 log.info("Started");
262 }
263
264 @Deactivate
265 public void deactivate() {
Frank Wange0eb5ce2016-07-01 18:21:25 +0800266 devicePortStats.removeListener(portStatsListener);
Madan Jampani632f16b2015-08-11 12:42:59 -0700267 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200268 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800269 executor.shutdownNow();
270
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800271 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700272 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800273 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700274 log.error("Timeout during executor shutdown");
275 }
276 } catch (InterruptedException e) {
277 log.error("Error during executor shutdown", e);
278 }
279
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700280 deviceDescs.clear();
281 devices.clear();
282 devicePorts.clear();
283 availableDevices.clear();
Frank Wange0eb5ce2016-07-01 18:21:25 +0800284 clusterCommunicator.removeSubscriber(
285 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE);
286 clusterCommunicator.removeSubscriber(
287 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE);
288 clusterCommunicator.removeSubscriber(
289 GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ);
290 clusterCommunicator.removeSubscriber(
291 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED);
292 clusterCommunicator.removeSubscriber(
293 GossipDeviceStoreMessageSubjects.PORT_UPDATE);
294 clusterCommunicator.removeSubscriber(
295 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE);
296 clusterCommunicator.removeSubscriber(
297 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE);
298 clusterCommunicator.removeSubscriber(
299 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED);
300 clusterCommunicator.removeSubscriber(
301 GossipDeviceStoreMessageSubjects.PORT_INJECTED);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700302 log.info("Stopped");
303 }
304
305 @Override
306 public int getDeviceCount() {
307 return devices.size();
308 }
309
310 @Override
311 public Iterable<Device> getDevices() {
312 return Collections.unmodifiableCollection(devices.values());
313 }
314
315 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800316 public Iterable<Device> getAvailableDevices() {
317 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700318 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800319 }
320
321 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700322 public Device getDevice(DeviceId deviceId) {
323 return devices.get(deviceId);
324 }
325
326 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700327 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700328 DeviceId deviceId,
329 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800330 NodeId localNode = clusterService.getLocalNode().id();
331 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
332
333 // Process device update only if we're the master,
334 // otherwise signal the actual master.
335 DeviceEvent deviceEvent = null;
336 if (localNode.equals(deviceNode)) {
337
338 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
339 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
340 final Timestamped<DeviceDescription> mergedDesc;
341 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
342
343 synchronized (device) {
344 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
345 mergedDesc = device.get(providerId).getDeviceDesc();
346 }
347
348 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700349 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
helenyrwufd296b62016-06-22 17:43:02 -0700350 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800351 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
352 }
353
354 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800355 // Only forward for ConfigProvider
356 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800357 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800358 return null;
359 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800360 // FIXME Temporary hack for NPE (ONOS-1171).
361 // Proper fix is to implement forwarding to master on ConfigProvider
362 // redo ONOS-490
363 if (deviceNode == null) {
364 // silently ignore
365 return null;
366 }
367
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800368
369 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
370 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800371
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800372 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700373 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800374 /* error log:
375 log.warn("Failed to process injected device id: {} desc: {} " +
376 "(cluster messaging failed: {})",
377 deviceId, deviceDescription, e);
378 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700379 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800380
381 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700382 }
383
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700384 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700385 DeviceId deviceId,
386 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700387
388 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800389 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700390 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700391
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800392 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700393 // locking per device
394
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700395 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
396 log.debug("Ignoring outdated event: {}", deltaDesc);
397 return null;
398 }
399
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800400 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700401
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700402 final Device oldDevice = devices.get(deviceId);
403 final Device newDevice;
404
405 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700406 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700407 // on new device or valid update
408 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800409 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700410 } else {
411 // outdated event, ignored.
412 return null;
413 }
414 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700415 // REGISTER
416 if (!deltaDesc.value().isDefaultAvailable()) {
417 return registerDevice(providerId, newDevice);
418 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700419 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700420 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700421 } else {
422 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700423 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
424 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700425 }
426 }
427 }
428
429 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700430 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700431 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700432 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700433
434 // update composed device cache
435 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
436 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700437 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
438 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700439
440 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700441 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700442 }
443
444 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
445 }
446
447 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700448 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700449 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700450 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700451 Device newDevice, Timestamp newTimestamp,
452 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700453 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700454 boolean propertiesChanged =
455 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700456 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
457 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700458 boolean annotationsChanged =
459 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700460
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700461 // Primary providers can respond to all changes, but ancillary ones
462 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800463 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700464 if ((providerId.isAncillary() && annotationsChanged) ||
465 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700466 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
467 if (!replaced) {
468 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700469 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800470 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700471 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700472
alshabibdc5d8bd2015-11-02 15:41:29 -0800473 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700474 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800475
helenyrwufd296b62016-06-22 17:43:02 -0700476 if (!providerId.isAncillary() && forceAvailable) {
alshabibdc5d8bd2015-11-02 15:41:29 -0800477 boolean wasOnline = availableDevices.contains(newDevice.id());
478 markOnline(newDevice.id(), newTimestamp);
479 if (!wasOnline) {
480 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
481 }
482 }
483 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700484 }
485
helenyrwufd296b62016-06-22 17:43:02 -0700486 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice) {
487 // update composed device cache
488 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
489 verify(oldDevice == null,
490 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
491 providerId, oldDevice, newDevice);
492
493 if (!providerId.isAncillary()) {
494 markOffline(newDevice.id());
495 }
496
497 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
498 }
499
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700500 @Override
501 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700502 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700503 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700504 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700505 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700506 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800507 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700508 }
509 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700510 }
511
512 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
513
514 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700515 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700516
517 // locking device
518 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700519
520 // accept off-line if given timestamp is newer than
521 // the latest Timestamp from Primary provider
522 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
523 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
524 if (timestamp.compareTo(lastTimestamp) <= 0) {
525 // outdated event ignore
526 return null;
527 }
528
529 offline.put(deviceId, timestamp);
530
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700531 Device device = devices.get(deviceId);
532 if (device == null) {
533 return null;
534 }
535 boolean removed = availableDevices.remove(deviceId);
536 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700537 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700538 }
539 return null;
540 }
541 }
542
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700543 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700544 public boolean markOnline(DeviceId deviceId) {
545 if (devices.containsKey(deviceId)) {
546 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
547 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
548 synchronized (deviceLock) {
549 if (markOnline(deviceId, timestamp)) {
550 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
551 return true;
552 } else {
553 return false;
554 }
555 }
556 }
557 log.warn("Device {} does not exist in store", deviceId);
558 return false;
559
560 }
561
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700562 /**
563 * Marks the device as available if the given timestamp is not outdated,
564 * compared to the time the device has been marked offline.
565 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700566 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700567 * @param timestamp of the event triggering this change.
568 * @return true if availability change request was accepted and changed the state
569 */
570 // Guarded by deviceDescs value (=Device lock)
571 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
572 // accept on-line if given timestamp is newer than
573 // the latest offline request Timestamp
574 Timestamp offlineTimestamp = offline.get(deviceId);
575 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700576 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700577
578 offline.remove(deviceId);
579 return availableDevices.add(deviceId);
580 }
581 return false;
582 }
583
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700584 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700585 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700586 DeviceId deviceId,
587 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700588
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800589 NodeId localNode = clusterService.getLocalNode().id();
590 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
591 // since it will trigger distributed store read.
592 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
593 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
594 // If we don't care much about topology performance, then it might be OK.
595 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700596
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800597 // Process port update only if we're the master of the device,
598 // otherwise signal the actual master.
599 List<DeviceEvent> deviceEvents = null;
600 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700601
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800602 final Timestamp newTimestamp;
603 try {
604 newTimestamp = deviceClockService.getTimestamp(deviceId);
605 } catch (IllegalStateException e) {
606 log.info("Timestamp was not available for device {}", deviceId);
607 log.debug(" discarding {}", portDescriptions);
608 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700609
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800610 // Possible situation:
611 // Device connected and became master for short period of time,
612 // but lost mastership before this instance had the chance to
613 // retrieve term information.
614
615 // Information dropped here is expected to be recoverable by
616 // device probing after mastership change
617
618 return Collections.emptyList();
619 }
620 log.debug("timestamp for {} {}", deviceId, newTimestamp);
621
622 final Timestamped<List<PortDescription>> timestampedInput
623 = new Timestamped<>(portDescriptions, newTimestamp);
624 final Timestamped<List<PortDescription>> merged;
625
626 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
627
628 synchronized (device) {
629 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
630 final DeviceDescriptions descs = device.get(providerId);
631 List<PortDescription> mergedList =
632 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700633 .transform(input ->
634 // lookup merged port description
635 descs.getPortDesc(input.portNumber()).value()
636 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700637 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800638 }
639
640 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700641 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700642 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800643 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
644 }
645
646 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800647 // Only forward for ConfigProvider
648 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800649 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta89461772016-01-26 12:18:10 -0800650 return Collections.emptyList();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800651 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800652 // FIXME Temporary hack for NPE (ONOS-1171).
653 // Proper fix is to implement forwarding to master on ConfigProvider
654 // redo ONOS-490
655 if (deviceNode == null) {
656 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800657 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800658 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800659
660 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800661
662 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700663 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800664 /* error log:
665 log.warn("Failed to process injected ports of device id: {} " +
666 "(cluster messaging failed: {})",
667 deviceId, e);
668 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700669 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700670
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800671 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700672 }
673
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700674 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700675 DeviceId deviceId,
676 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700677
678 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700679 if (device == null) {
680 log.debug("Device is no longer valid: {}", deviceId);
681 return Collections.emptyList();
682 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700683
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700684 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700685 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
686
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700687 List<DeviceEvent> events = new ArrayList<>();
688 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700689
690 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
691 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700692 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700693 }
694
695 DeviceDescriptions descs = descsMap.get(providerId);
696 // every provider must provide DeviceDescription.
697 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700698 "Device description for Device ID %s from Provider %s was not found",
699 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700700
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700701 Map<PortNumber, Port> ports = getPortMap(deviceId);
702
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700703 final Timestamp newTimestamp = portDescriptions.timestamp();
704
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700705 // Add new ports
706 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700707 for (PortDescription portDescription : portDescriptions.value()) {
708 final PortNumber number = portDescription.portNumber();
709 processed.add(number);
710
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700711 final Port oldPort = ports.get(number);
712 final Port newPort;
713
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700714
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700715 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
716 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700717 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700718 // on new port or valid update
719 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700720 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700721 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700722 newPort = composePort(device, number, descsMap);
723 } else {
724 // outdated event, ignored.
725 continue;
726 }
727
728 events.add(oldPort == null ?
729 createPort(device, newPort, ports) :
730 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700731 }
732
733 events.addAll(pruneOldPorts(device, ports, processed));
734 }
735 return FluentIterable.from(events).filter(notNull()).toList();
736 }
737
738 // Creates a new port based on the port description adds it to the map and
739 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700740 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700741 private DeviceEvent createPort(Device device, Port newPort,
742 Map<PortNumber, Port> ports) {
743 ports.put(newPort.number(), newPort);
744 return new DeviceEvent(PORT_ADDED, device, newPort);
745 }
746
747 // Checks if the specified port requires update and if so, it replaces the
748 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700749 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700750 private DeviceEvent updatePort(Device device, Port oldPort,
751 Port newPort,
752 Map<PortNumber, Port> ports) {
753 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700754 oldPort.type() != newPort.type() ||
755 oldPort.portSpeed() != newPort.portSpeed() ||
756 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700757 ports.put(oldPort.number(), newPort);
758 return new DeviceEvent(PORT_UPDATED, device, newPort);
759 }
760 return null;
761 }
762
763 // Prunes the specified list of ports based on which ports are in the
764 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700765 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700766 private List<DeviceEvent> pruneOldPorts(Device device,
767 Map<PortNumber, Port> ports,
768 Set<PortNumber> processed) {
769 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700770 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700771 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700772 Entry<PortNumber, Port> e = iterator.next();
773 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700774 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700775 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700776 iterator.remove();
777 }
778 }
779 return events;
780 }
781
782 // Gets the map of ports for the specified device; if one does not already
783 // exist, it creates and registers a new one.
784 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700785 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700786 }
787
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700788 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700789 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700790 Map<ProviderId, DeviceDescriptions> r;
791 r = deviceDescs.get(deviceId);
792 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700793 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700794 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
795 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
796 if (concurrentlyAdded != null) {
797 r = concurrentlyAdded;
798 }
799 }
800 return r;
801 }
802
803 // Guarded by deviceDescs value (=Device lock)
804 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
805 Map<ProviderId, DeviceDescriptions> device,
806 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700807 synchronized (device) {
808 DeviceDescriptions r = device.get(providerId);
809 if (r == null) {
810 r = new DeviceDescriptions(deltaDesc);
811 device.put(providerId, r);
812 }
813 return r;
814 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700815 }
816
817 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700818 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
819 DeviceId deviceId,
820 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700821 final Timestamp newTimestamp;
822 try {
823 newTimestamp = deviceClockService.getTimestamp(deviceId);
824 } catch (IllegalStateException e) {
825 log.info("Timestamp was not available for device {}", deviceId);
826 log.debug(" discarding {}", portDescription);
827 // Failed to generate timestamp. Ignoring.
828 // See updatePorts comment
829 return null;
830 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700831 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700832 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700833 final DeviceEvent event;
834 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800835 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
836 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700837 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800838 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700839 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700840 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700841 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700842 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700843 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800844 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700845 }
846 return event;
847 }
848
849 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700850 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700851 Device device = devices.get(deviceId);
852 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
853
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700854 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700855 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
856
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700857 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700858
859 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
860 log.debug("Ignoring outdated event: {}", deltaDesc);
861 return null;
862 }
863
864 DeviceDescriptions descs = descsMap.get(providerId);
865 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700866 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700867 "Device description for Device ID %s from Provider %s was not found",
868 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700869
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700870 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
871 final PortNumber number = deltaDesc.value().portNumber();
872 final Port oldPort = ports.get(number);
873 final Port newPort;
874
875 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
876 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700877 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700878 // on new port or valid update
879 // update description
880 descs.putPortDesc(deltaDesc);
881 newPort = composePort(device, number, descsMap);
882 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700883 // same or outdated event, ignored.
884 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700885 return null;
886 }
887
888 if (oldPort == null) {
889 return createPort(device, newPort, ports);
890 } else {
891 return updatePort(device, oldPort, newPort, ports);
892 }
893 }
894 }
895
896 @Override
897 public List<Port> getPorts(DeviceId deviceId) {
898 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
899 if (ports == null) {
900 return Collections.emptyList();
901 }
902 return ImmutableList.copyOf(ports.values());
903 }
904
905 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700906 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
907 DeviceId deviceId) {
908 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
909 if (descs == null) {
910 return null;
911 }
912 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
913 final Optional<DeviceDescriptions> devDescs;
914 synchronized (descs) {
915 devDescs = Optional.ofNullable(descs.get(pid));
916 }
917 // DeviceDescriptions is concurrent access-safe
918 return devDescs
919 .map(dd -> dd.getPortDescs().values().stream()
920 .map(Timestamped::value))
921 .orElse(Stream.empty());
922 }
923
924 @Override
sangho538108b2015-04-08 14:29:20 -0700925 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200926 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700927
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200928 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
929 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
930 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
931
932 if (prvStatsMap != null) {
933 for (PortStatistics newStats : newStatsCollection) {
934 PortNumber port = PortNumber.portNumber(newStats.port());
935 PortStatistics prvStats = prvStatsMap.get(port);
936 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
937 PortStatistics deltaStats = builder.build();
938 if (prvStats != null) {
939 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
940 }
941 deltaStatsMap.put(port, deltaStats);
942 newStatsMap.put(port, newStats);
943 }
944 } else {
945 for (PortStatistics newStats : newStatsCollection) {
946 PortNumber port = PortNumber.portNumber(newStats.port());
947 newStatsMap.put(port, newStats);
948 }
sangho538108b2015-04-08 14:29:20 -0700949 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200950 devicePortDeltaStats.put(deviceId, deltaStatsMap);
951 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200952 // DeviceEvent returns null because of InternalPortStatsListener usage
953 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200954 }
955
956 /**
957 * Calculate delta statistics by subtracting previous from new statistics.
958 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700959 * @param deviceId device identifier
960 * @param prvStats previous port statistics
961 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200962 * @return PortStatistics
963 */
964 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
965 // calculate time difference
966 long deltaStatsSec, deltaStatsNano;
967 if (newStats.durationNano() < prvStats.durationNano()) {
968 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
969 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
970 } else {
971 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
972 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
973 }
974 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
975 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
976 .setPort(newStats.port())
977 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
978 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
979 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
980 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
981 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
982 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
983 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
984 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
985 .setDurationSec(deltaStatsSec)
986 .setDurationNano(deltaStatsNano)
987 .build();
988 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700989 }
990
991 @Override
992 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700993 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
994 if (portStats == null) {
995 return Collections.emptyList();
996 }
997 return ImmutableList.copyOf(portStats.values());
998 }
999
1000 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +05301001 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
1002 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
1003 if (portStatsMap == null) {
1004 return null;
1005 }
1006 PortStatistics portStats = portStatsMap.get(portNumber);
1007 return portStats;
1008 }
1009
1010 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001011 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
1012 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
1013 if (portStats == null) {
1014 return Collections.emptyList();
1015 }
1016 return ImmutableList.copyOf(portStats.values());
1017 }
1018
1019 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +05301020 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
1021 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
1022 if (portStatsMap == null) {
1023 return null;
1024 }
1025 PortStatistics portStats = portStatsMap.get(portNumber);
1026 return portStats;
1027 }
1028
1029 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001030 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
1031 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1032 return ports == null ? null : ports.get(portNumber);
1033 }
1034
1035 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -07001036 public PortDescription getPortDescription(ProviderId pid,
1037 DeviceId deviceId,
1038 PortNumber portNumber) {
1039 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1040 if (descs == null) {
1041 return null;
1042 }
1043 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1044 final Optional<DeviceDescriptions> devDescs;
1045 synchronized (descs) {
1046 devDescs = Optional.ofNullable(descs.get(pid));
1047 }
1048 // DeviceDescriptions is concurrent access-safe
1049 return devDescs
1050 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1051 .map(Timestamped::value)
1052 .orElse(null);
1053 }
1054
1055 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001056 public boolean isAvailable(DeviceId deviceId) {
1057 return availableDevices.contains(deviceId);
1058 }
1059
1060 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001061 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001062 final NodeId myId = clusterService.getLocalNode().id();
1063 NodeId master = mastershipService.getMasterFor(deviceId);
1064
1065 // if there exist a master, forward
1066 // if there is no master, try to become one and process
1067
1068 boolean relinquishAtEnd = false;
1069 if (master == null) {
1070 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1071 if (myRole != MastershipRole.NONE) {
1072 relinquishAtEnd = true;
1073 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001074 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001075 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001076 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -07001077 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001078 master = myId;
1079 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001080 }
1081
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001082 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001083 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001084 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001085
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001086 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001087 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001088 /* error log:
1089 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1090 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001091
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001092 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001093 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001094 }
1095
1096 // I have control..
1097
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -07001098 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001099 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001100 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001101 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001102 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001103 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001104 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001105 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001106 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001107 mastershipService.relinquishMastership(deviceId);
1108 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001109 return event;
1110 }
1111
1112 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
1113 Timestamp timestamp) {
1114
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001115 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001116 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001117 // accept removal request if given timestamp is newer than
1118 // the latest Timestamp from Primary provider
1119 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001120 if (primDescs == null) {
1121 return null;
1122 }
1123
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001124 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
1125 if (timestamp.compareTo(lastTimestamp) <= 0) {
1126 // outdated event ignore
1127 return null;
1128 }
1129 removalRequest.put(deviceId, timestamp);
1130
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001131 Device device = devices.remove(deviceId);
1132 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001133 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1134 if (ports != null) {
1135 ports.clear();
1136 }
1137 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001138 descs.clear();
1139 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001140 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001141 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001142 }
1143
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001144 /**
1145 * Checks if given timestamp is superseded by removal request
1146 * with more recent timestamp.
1147 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001148 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001149 * @param timestampToCheck timestamp of an event to check
1150 * @return true if device is already removed
1151 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001152 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1153 Timestamp removalTimestamp = removalRequest.get(deviceId);
1154 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001155 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001156 // removalRequest is more recent
1157 return true;
1158 }
1159 return false;
1160 }
1161
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001162 /**
1163 * Returns a Device, merging description given from multiple Providers.
1164 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001165 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001166 * @param providerDescs Collection of Descriptions from multiple providers
1167 * @return Device instance
1168 */
1169 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001170 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001171
Thomas Vachuska444eda62014-10-28 13:09:42 -07001172 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001173
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001174 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001175
1176 DeviceDescriptions desc = providerDescs.get(primary);
1177
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001178 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001179 Type type = base.type();
1180 String manufacturer = base.manufacturer();
1181 String hwVersion = base.hwVersion();
1182 String swVersion = base.swVersion();
1183 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001184 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001185 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1186 annotations = merge(annotations, base.annotations());
1187
1188 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1189 if (e.getKey().equals(primary)) {
1190 continue;
1191 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001192 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001193 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001194 // Currently assuming there will never be a key conflict between
1195 // providers
1196
1197 // annotation merging. not so efficient, should revisit later
1198 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1199 }
1200
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001201 return new DefaultDevice(primary, deviceId, type, manufacturer,
1202 hwVersion, swVersion, serialNumber,
1203 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001204 }
1205
Marc De Leenheer88194c32015-05-29 22:10:59 -07001206 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1207 PortDescription description, Annotations annotations) {
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001208 // FIXME this switch need to go away once all ports are done.
Marc De Leenheer88194c32015-05-29 22:10:59 -07001209 switch (description.type()) {
1210 case OMS:
HIGUCHI Yuta95d83e82016-04-26 12:13:48 -07001211 if (description instanceof OmsPortDescription) {
1212 // remove if-block once deprecation is complete
1213 OmsPortDescription omsDesc = (OmsPortDescription) description;
1214 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1215 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1216 }
1217 // same as default
1218 return new DefaultPort(device, number, isEnabled, description.type(),
1219 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001220 case OCH:
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001221 if (description instanceof OchPortDescription) {
1222 // remove if-block once Och deprecation is complete
1223 OchPortDescription ochDesc = (OchPortDescription) description;
1224 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1225 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1226 }
1227 return new DefaultPort(device, number, isEnabled, description.type(),
1228 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001229 case ODUCLT:
HIGUCHI Yuta4c0ef6b2016-05-02 19:45:41 -07001230 if (description instanceof OduCltPortDescription) {
1231 // remove if-block once deprecation is complete
1232 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1233 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1234 }
1235 // same as default
1236 return new DefaultPort(device, number, isEnabled, description.type(),
1237 description.portSpeed(), annotations);
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +02001238 case OTU:
HIGUCHI Yuta5be3e822016-05-03 13:51:42 -07001239 if (description instanceof OtuPortDescription) {
1240 // remove if-block once deprecation is complete
1241 OtuPortDescription otuDesc = (OtuPortDescription) description;
1242 return new OtuPort(device, number, isEnabled, otuDesc.signalType(), annotations);
1243 }
1244 // same as default
1245 return new DefaultPort(device, number, isEnabled, description.type(),
1246 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001247 default:
1248 return new DefaultPort(device, number, isEnabled, description.type(),
1249 description.portSpeed(), annotations);
1250 }
1251 }
1252
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001253 /**
1254 * Returns a Port, merging description given from multiple Providers.
1255 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001256 * @param device device the port is on
1257 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001258 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001259 * @return Port instance
1260 */
1261 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001262 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001263
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001264 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001265 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001266 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001267 boolean isEnabled = false;
1268 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001269 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001270 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1271 if (portDesc != null) {
1272 isEnabled = portDesc.value().isEnabled();
1273 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001274 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001275 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001276 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001277 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001278 if (e.getKey().equals(primary)) {
1279 continue;
1280 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001281 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001282 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001283 // Currently assuming there will never be a key conflict between
1284 // providers
1285
1286 // annotation merging. not so efficient, should revisit later
1287 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1288 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001289 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1290 continue;
1291 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001292 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001293 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001294 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001295 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001296 }
1297 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001298 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001299 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001300 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001301 PortDescription current = portDesc.value();
1302 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001303 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001304 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001305 }
1306
1307 /**
1308 * @return primary ProviderID, or randomly chosen one if none exists
1309 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001310 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001311 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001312 ProviderId fallBackPrimary = null;
1313 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1314 if (!e.getKey().isAncillary()) {
1315 return e.getKey();
1316 } else if (fallBackPrimary == null) {
1317 // pick randomly as a fallback in case there is no primary
1318 fallBackPrimary = e.getKey();
1319 }
1320 }
1321 return fallBackPrimary;
1322 }
1323
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001324 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001325 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001326 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001327 return providerDescs.get(pid);
1328 }
1329
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001330 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001331 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001332 }
1333
Jonathan Hart7d656f42015-01-27 14:07:23 -08001334 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001335 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001336 }
Madan Jampani47c93732014-10-06 20:46:08 -07001337
Jonathan Hart7d656f42015-01-27 14:07:23 -08001338 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001339 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001340 }
1341
Jonathan Hart7d656f42015-01-27 14:07:23 -08001342 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001343 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001344 }
1345
Jonathan Hart7d656f42015-01-27 14:07:23 -08001346 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001347 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001348 }
1349
Jonathan Hart7d656f42015-01-27 14:07:23 -08001350 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001351 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001352 }
1353
Jonathan Hart7d656f42015-01-27 14:07:23 -08001354 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001355 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1356 }
1357
1358 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1359 try {
1360 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1361 } catch (IOException e) {
1362 log.error("Failed to send" + event + " to " + recipient, e);
1363 }
1364 }
1365
1366 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1367 try {
1368 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1369 } catch (IOException e) {
1370 log.error("Failed to send" + event + " to " + recipient, e);
1371 }
1372 }
1373
1374 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1375 try {
1376 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1377 } catch (IOException e) {
1378 log.error("Failed to send" + event + " to " + recipient, e);
1379 }
1380 }
1381
1382 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1383 try {
1384 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1385 } catch (IOException e) {
1386 log.error("Failed to send" + event + " to " + recipient, e);
1387 }
1388 }
1389
1390 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1391 try {
1392 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1393 } catch (IOException e) {
1394 log.error("Failed to send" + event + " to " + recipient, e);
1395 }
1396 }
1397
1398 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1399 final NodeId self = clusterService.getLocalNode().id();
1400
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001401 final int numDevices = deviceDescs.size();
1402 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1403 final int portsPerDevice = 8; // random factor to minimize reallocation
1404 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1405 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001406
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001407 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001408
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001409 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001410 synchronized (devDescs) {
1411
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001412 // send device offline timestamp
1413 Timestamp lOffline = this.offline.get(deviceId);
1414 if (lOffline != null) {
1415 adOffline.put(deviceId, lOffline);
1416 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001417
1418 for (Entry<ProviderId, DeviceDescriptions>
1419 prov : devDescs.entrySet()) {
1420
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001421 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001422 final ProviderId provId = prov.getKey();
1423 final DeviceDescriptions descs = prov.getValue();
1424
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001425 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001426 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001427
1428 for (Entry<PortNumber, Timestamped<PortDescription>>
1429 portDesc : descs.getPortDescs().entrySet()) {
1430
1431 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001432 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001433 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001434 }
1435 }
1436 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001437 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001438
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001439 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001440 }
1441
1442 /**
1443 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001444 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001445 * Notify sender about out-dated information using regular replication message.
1446 * Send back advertisement to sender if not in sync.
1447 *
1448 * @param advertisement to respond to
1449 */
1450 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1451
1452 final NodeId sender = advertisement.sender();
1453
1454 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1455 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1456 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1457
1458 // Fragments to request
1459 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1460 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1461
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001462 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001463 final DeviceId deviceId = de.getKey();
1464 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1465
1466 synchronized (lDevice) {
1467 // latestTimestamp across provider
1468 // Note: can be null initially
1469 Timestamp localLatest = offline.get(deviceId);
1470
1471 // handle device Ads
1472 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1473 final ProviderId provId = prov.getKey();
1474 final DeviceDescriptions lDeviceDescs = prov.getValue();
1475
1476 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1477
1478
1479 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1480 Timestamp advDevTimestamp = devAds.get(devFragId);
1481
Jonathan Hart403ea932015-02-20 16:23:00 -08001482 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1483 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001484 // remote does not have it or outdated, suggest
1485 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1486 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1487 // local is outdated, request
1488 reqDevices.add(devFragId);
1489 }
1490
1491 // handle port Ads
1492 for (Entry<PortNumber, Timestamped<PortDescription>>
1493 pe : lDeviceDescs.getPortDescs().entrySet()) {
1494
1495 final PortNumber num = pe.getKey();
1496 final Timestamped<PortDescription> lPort = pe.getValue();
1497
1498 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1499
1500 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001501 if (advPortTimestamp == null || lPort.isNewerThan(
1502 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001503 // remote does not have it or outdated, suggest
1504 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1505 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1506 // local is outdated, request
1507 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1508 reqPorts.add(portFragId);
1509 }
1510
1511 // remove port Ad already processed
1512 portAds.remove(portFragId);
1513 } // end local port loop
1514
1515 // remove device Ad already processed
1516 devAds.remove(devFragId);
1517
1518 // find latest and update
1519 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1520 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001521 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001522 localLatest = providerLatest;
1523 }
1524 } // end local provider loop
1525
1526 // checking if remote timestamp is more recent.
1527 Timestamp rOffline = offlineAds.get(deviceId);
1528 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001529 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001530 // remote offline timestamp suggests that the
1531 // device is off-line
1532 markOfflineInternal(deviceId, rOffline);
1533 }
1534
1535 Timestamp lOffline = offline.get(deviceId);
1536 if (lOffline != null && rOffline == null) {
1537 // locally offline, but remote is online, suggest offline
1538 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1539 }
1540
1541 // remove device offline Ad already processed
1542 offlineAds.remove(deviceId);
1543 } // end local device loop
1544 } // device lock
1545
1546 // If there is any Ads left, request them
1547 log.trace("Ads left {}, {}", devAds, portAds);
1548 reqDevices.addAll(devAds.keySet());
1549 reqPorts.addAll(portAds.keySet());
1550
1551 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1552 log.trace("Nothing to request to remote peer {}", sender);
1553 return;
1554 }
1555
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001556 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001557
1558 // 2-way Anti-Entropy for now
1559 try {
1560 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1561 } catch (IOException e) {
1562 log.error("Failed to send response advertisement to " + sender, e);
1563 }
1564
1565// Sketch of 3-way Anti-Entropy
1566// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1567// ClusterMessage message = new ClusterMessage(
1568// clusterService.getLocalNode().id(),
1569// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1570// SERIALIZER.encode(request));
1571//
1572// try {
1573// clusterCommunicator.unicast(message, advertisement.sender());
1574// } catch (IOException e) {
1575// log.error("Failed to send advertisement reply to "
1576// + advertisement.sender(), e);
1577// }
Madan Jampani47c93732014-10-06 20:46:08 -07001578 }
1579
Madan Jampani255a58b2014-10-09 12:08:20 -07001580 private void notifyDelegateIfNotNull(DeviceEvent event) {
1581 if (event != null) {
1582 notifyDelegate(event);
1583 }
1584 }
1585
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001586 private final class SendAdvertisementTask implements Runnable {
1587
1588 @Override
1589 public void run() {
1590 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001591 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001592 return;
1593 }
1594
1595 try {
1596 final NodeId self = clusterService.getLocalNode().id();
1597 Set<ControllerNode> nodes = clusterService.getNodes();
1598
1599 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1600 .transform(toNodeId())
1601 .toList();
1602
1603 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001604 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001605 return;
1606 }
1607
1608 NodeId peer;
1609 do {
1610 int idx = RandomUtils.nextInt(0, nodeIds.size());
1611 peer = nodeIds.get(idx);
1612 } while (peer.equals(self));
1613
1614 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1615
1616 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001617 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001618 return;
1619 }
1620
1621 try {
1622 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1623 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001624 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001625 return;
1626 }
1627 } catch (Exception e) {
1628 // catch all Exception to avoid Scheduled task being suppressed.
1629 log.error("Exception thrown while sending advertisement", e);
1630 }
1631 }
1632 }
1633
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001634 private final class InternalDeviceEventListener
1635 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001636 @Override
1637 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001638 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001639 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001640
Madan Jampani47c93732014-10-06 20:46:08 -07001641 ProviderId providerId = event.providerId();
1642 DeviceId deviceId = event.deviceId();
1643 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001644
Madan Jampani2af244a2015-02-22 13:12:01 -08001645 try {
helenyrwufd296b62016-06-22 17:43:02 -07001646 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1647 deviceDescription));
Madan Jampani2af244a2015-02-22 13:12:01 -08001648 } catch (Exception e) {
1649 log.warn("Exception thrown handling device update", e);
1650 }
Madan Jampani47c93732014-10-06 20:46:08 -07001651 }
1652 }
1653
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001654 private final class InternalDeviceOfflineEventListener
1655 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001656 @Override
1657 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001658 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001659 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001660
1661 DeviceId deviceId = event.deviceId();
1662 Timestamp timestamp = event.timestamp();
1663
Madan Jampani2af244a2015-02-22 13:12:01 -08001664 try {
1665 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1666 } catch (Exception e) {
1667 log.warn("Exception thrown handling device offline", e);
1668 }
Madan Jampani25322532014-10-08 11:20:38 -07001669 }
1670 }
1671
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001672 private final class InternalRemoveRequestListener
1673 implements ClusterMessageHandler {
1674 @Override
1675 public void handle(ClusterMessage message) {
1676 log.debug("Received device remove request from peer: {}", message.sender());
1677 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001678
Madan Jampani2af244a2015-02-22 13:12:01 -08001679 try {
1680 removeDevice(did);
1681 } catch (Exception e) {
1682 log.warn("Exception thrown handling device remove", e);
1683 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001684 }
1685 }
1686
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001687 private final class InternalDeviceRemovedEventListener
1688 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001689 @Override
1690 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001691 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001692 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001693
1694 DeviceId deviceId = event.deviceId();
1695 Timestamp timestamp = event.timestamp();
1696
Madan Jampani2af244a2015-02-22 13:12:01 -08001697 try {
1698 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1699 } catch (Exception e) {
1700 log.warn("Exception thrown handling device removed", e);
1701 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001702 }
1703 }
1704
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001705 private final class InternalPortEventListener
1706 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001707 @Override
1708 public void handle(ClusterMessage message) {
1709
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001710 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001711 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001712
1713 ProviderId providerId = event.providerId();
1714 DeviceId deviceId = event.deviceId();
1715 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1716
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001717 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001718 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001719 // Note: dropped information will be recovered by anti-entropy
1720 return;
1721 }
1722
Madan Jampani2af244a2015-02-22 13:12:01 -08001723 try {
1724 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1725 } catch (Exception e) {
1726 log.warn("Exception thrown handling port update", e);
1727 }
Madan Jampani47c93732014-10-06 20:46:08 -07001728 }
1729 }
1730
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001731 private final class InternalPortStatusEventListener
1732 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001733 @Override
1734 public void handle(ClusterMessage message) {
1735
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001736 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001737 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001738
1739 ProviderId providerId = event.providerId();
1740 DeviceId deviceId = event.deviceId();
1741 Timestamped<PortDescription> portDescription = event.portDescription();
1742
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001743 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001744 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001745 // Note: dropped information will be recovered by anti-entropy
1746 return;
1747 }
1748
Madan Jampani2af244a2015-02-22 13:12:01 -08001749 try {
1750 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1751 } catch (Exception e) {
1752 log.warn("Exception thrown handling port update", e);
1753 }
Madan Jampani47c93732014-10-06 20:46:08 -07001754 }
1755 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001756
1757 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001758 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001759 @Override
1760 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001761 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001762 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001763 try {
1764 handleAdvertisement(advertisement);
1765 } catch (Exception e) {
1766 log.warn("Exception thrown handling Device advertisements.", e);
1767 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001768 }
1769 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001770
1771 private final class DeviceInjectedEventListener
1772 implements ClusterMessageHandler {
1773 @Override
1774 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001775 log.debug("Received injected device event from peer: {}", message.sender());
1776 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1777
1778 ProviderId providerId = event.providerId();
1779 DeviceId deviceId = event.deviceId();
1780 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001781 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1782 // workaround for ONOS-1208
1783 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1784 return;
1785 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001786
Madan Jampani2af244a2015-02-22 13:12:01 -08001787 try {
1788 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1789 } catch (Exception e) {
1790 log.warn("Exception thrown handling device injected event.", e);
1791 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001792 }
1793 }
1794
1795 private final class PortInjectedEventListener
1796 implements ClusterMessageHandler {
1797 @Override
1798 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001799 log.debug("Received injected port event from peer: {}", message.sender());
1800 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1801
1802 ProviderId providerId = event.providerId();
1803 DeviceId deviceId = event.deviceId();
1804 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001805 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1806 // workaround for ONOS-1208
1807 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1808 return;
1809 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001810
Madan Jampani2af244a2015-02-22 13:12:01 -08001811 try {
1812 updatePorts(providerId, deviceId, portDescriptions);
1813 } catch (Exception e) {
1814 log.warn("Exception thrown handling port injected event.", e);
1815 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001816 }
1817 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001818
1819 private class InternalPortStatsListener
1820 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1821 @Override
1822 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1823 if (event.type() == PUT) {
1824 Device device = devices.get(event.key());
1825 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001826 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001827 }
1828 }
1829 }
1830 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001831}