blob: 06043ea310a4529cdc1e774bfc3f5d2c053c6853 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2014-present Open Networking Laboratory
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.store.device.impl;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070017
Jonathan Hart46ab5cc2016-09-15 15:42:39 -070018import com.google.common.collect.FluentIterable;
19import com.google.common.collect.ImmutableList;
20import com.google.common.collect.Maps;
21import com.google.common.collect.Sets;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070022import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070023import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
26import org.apache.felix.scr.annotations.Reference;
27import org.apache.felix.scr.annotations.ReferenceCardinality;
28import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080029import org.onlab.packet.ChassisId;
30import org.onlab.util.KryoNamespace;
Brian O'Connorabafb502014-12-02 22:26:20 -080031import org.onosproject.cluster.ClusterService;
32import org.onosproject.cluster.ControllerNode;
33import org.onosproject.cluster.NodeId;
34import org.onosproject.mastership.MastershipService;
35import org.onosproject.mastership.MastershipTerm;
36import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070037import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080038import org.onosproject.net.AnnotationsUtil;
39import org.onosproject.net.DefaultAnnotations;
40import org.onosproject.net.DefaultDevice;
41import org.onosproject.net.DefaultPort;
42import org.onosproject.net.Device;
43import org.onosproject.net.Device.Type;
44import org.onosproject.net.DeviceId;
45import org.onosproject.net.MastershipRole;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070046import org.onosproject.net.OchPort;
47import org.onosproject.net.OduCltPort;
48import org.onosproject.net.OmsPort;
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +020049import org.onosproject.net.OtuPort;
Brian O'Connorabafb502014-12-02 22:26:20 -080050import org.onosproject.net.Port;
51import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070052import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080053import org.onosproject.net.device.DeviceClockService;
54import org.onosproject.net.device.DeviceDescription;
55import org.onosproject.net.device.DeviceEvent;
56import org.onosproject.net.device.DeviceStore;
57import org.onosproject.net.device.DeviceStoreDelegate;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070058import org.onosproject.net.device.OchPortDescription;
59import org.onosproject.net.device.OduCltPortDescription;
60import org.onosproject.net.device.OmsPortDescription;
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +020061import org.onosproject.net.device.OtuPortDescription;
Brian O'Connorabafb502014-12-02 22:26:20 -080062import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070063import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080064import org.onosproject.net.provider.ProviderId;
65import org.onosproject.store.AbstractStore;
66import org.onosproject.store.Timestamp;
67import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
Brian O'Connorabafb502014-12-02 22:26:20 -080068import org.onosproject.store.cluster.messaging.MessageSubject;
69import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070070import org.onosproject.store.serializers.KryoNamespaces;
HIGUCHI Yutae7290652016-05-18 11:29:01 -070071import org.onosproject.store.serializers.StoreSerializer;
Brian O'Connor6de2e202015-05-21 14:30:41 -070072import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070073import org.onosproject.store.service.EventuallyConsistentMap;
74import org.onosproject.store.service.EventuallyConsistentMapEvent;
75import org.onosproject.store.service.EventuallyConsistentMapListener;
76import org.onosproject.store.service.MultiValuedTimestamp;
77import org.onosproject.store.service.StorageService;
78import org.onosproject.store.service.WallClockTimestamp;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070079import org.slf4j.Logger;
80
Jonathan Hart46ab5cc2016-09-15 15:42:39 -070081import java.io.IOException;
82import java.util.ArrayList;
83import java.util.Collection;
84import java.util.Collections;
85import java.util.HashMap;
86import java.util.HashSet;
87import java.util.Iterator;
88import java.util.List;
89import java.util.Map;
90import java.util.Map.Entry;
91import java.util.Objects;
92import java.util.Optional;
93import java.util.Set;
94import java.util.concurrent.ConcurrentHashMap;
95import java.util.concurrent.ConcurrentMap;
96import java.util.concurrent.ExecutorService;
97import java.util.concurrent.ScheduledExecutorService;
98import java.util.concurrent.TimeUnit;
99import java.util.function.Consumer;
100import java.util.stream.Stream;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700101
102import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700103import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700104import static com.google.common.base.Verify.verify;
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800105import static java.util.concurrent.Executors.newCachedThreadPool;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800106import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800107import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800108import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800109import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
110import static org.onosproject.net.DefaultAnnotations.merge;
Ray Milkey9ef22232016-07-14 12:42:37 -0700111import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED;
112import static org.onosproject.net.device.DeviceEvent.Type.PORT_ADDED;
113import static org.onosproject.net.device.DeviceEvent.Type.PORT_REMOVED;
114import static org.onosproject.net.device.DeviceEvent.Type.PORT_STATS_UPDATED;
115import static org.onosproject.net.device.DeviceEvent.Type.PORT_UPDATED;
116import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE;
117import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_INJECTED;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700118import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE;
119import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVED;
Ray Milkey9ef22232016-07-14 12:42:37 -0700120import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700121import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_UPDATE;
Ray Milkey9ef22232016-07-14 12:42:37 -0700122import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_INJECTED;
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700123import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE;
124import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_UPDATE;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700125import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800126import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700127
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700128/**
129 * Manages inventory of infrastructure devices using gossip protocol to distribute
130 * information.
131 */
132@Component(immediate = true)
133@Service
134public class GossipDeviceStore
135 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
136 implements DeviceStore {
137
138 private final Logger log = getLogger(getClass());
139
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700140 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800141 // Timeout in milliseconds to process device or ports on remote master node
142 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700143
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700144 // innerMap is used to lock a Device, thus instance should never be replaced.
145 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700146 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700147 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700148
149 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700150 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
151 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700152
153 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200154 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700155 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
156 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700157
158 // to be updated under Device lock
159 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
160 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700161
162 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700163 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700164
165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700166 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700167
Madan Jampani47c93732014-10-06 20:46:08 -0700168 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700169 protected StorageService storageService;
170
171 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700172 protected ClusterCommunicationService clusterCommunicator;
173
Madan Jampani53e44e62014-10-07 12:39:51 -0700174 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
175 protected ClusterService clusterService;
176
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700177 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
178 protected MastershipService mastershipService;
179
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800180 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
181 protected MastershipTermService termService;
182
183
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700184 protected static final StoreSerializer SERIALIZER = StoreSerializer.using(KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800185 .register(DistributedStoreSerializers.STORE_COMMON)
186 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
187 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
188 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700189 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800190 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
191 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700192 .register(DeviceAntiEntropyAdvertisement.class)
193 .register(DeviceFragmentId.class)
194 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800195 .register(DeviceInjectedEvent.class)
196 .register(PortInjectedEvent.class)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700197 .build("GossipDevice"));
Madan Jampani53e44e62014-10-07 12:39:51 -0700198
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800199 private ExecutorService executor;
200
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800201 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700202
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800203 // TODO make these anti-entropy parameters configurable
204 private long initialDelaySec = 5;
205 private long periodSec = 5;
206
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700207 @Activate
208 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800209 executor = newCachedThreadPool(groupedThreads("onos/device", "fg-%d", log));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800210
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800211 backgroundExecutor =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800212 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d", log)));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700213
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700214 addSubscriber(DEVICE_UPDATE, this::handleDeviceEvent);
215 addSubscriber(DEVICE_OFFLINE, this::handleDeviceOfflineEvent);
216 addSubscriber(DEVICE_REMOVE_REQ, this::handleRemoveRequest);
217 addSubscriber(DEVICE_REMOVED, this::handleDeviceRemovedEvent);
218 addSubscriber(PORT_UPDATE, this::handlePortEvent);
219 addSubscriber(PORT_STATUS_UPDATE, this::handlePortStatusEvent);
220 addSubscriber(DEVICE_ADVERTISE, this::handleDeviceAdvertisement);
221 addSubscriber(DEVICE_INJECTED, this::handleDeviceInjectedEvent);
222 addSubscriber(PORT_INJECTED, this::handlePortInjectedEvent);
Madan Jampani2af244a2015-02-22 13:12:01 -0800223
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700224 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800225 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700226 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700227
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700228 // Create a distributed map for port stats.
229 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
230 .register(KryoNamespaces.API)
HIGUCHI Yuta03666a32016-05-18 11:49:09 -0700231 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
232 .register(MultiValuedTimestamp.class);
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700233
234 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
235 .withName("port-stats")
236 .withSerializer(deviceDataSerializer)
237 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700238 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700239 .withTombstonesDisabled()
240 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200241 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
242 eventuallyConsistentMapBuilder()
243 .withName("port-stats-delta")
244 .withSerializer(deviceDataSerializer)
245 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
246 .withTimestampProvider((k, v) -> new WallClockTimestamp())
247 .withTombstonesDisabled()
248 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700249 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700250 log.info("Started");
251 }
252
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700253 private <M> void addSubscriber(MessageSubject subject, Consumer<M> handler) {
254 clusterCommunicator.addSubscriber(subject, SERIALIZER::decode, handler, executor);
255 }
256
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700257 @Deactivate
258 public void deactivate() {
Frank Wange0eb5ce2016-07-01 18:21:25 +0800259 devicePortStats.removeListener(portStatsListener);
Madan Jampani632f16b2015-08-11 12:42:59 -0700260 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200261 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800262 executor.shutdownNow();
263
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800264 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700265 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800266 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700267 log.error("Timeout during executor shutdown");
268 }
269 } catch (InterruptedException e) {
270 log.error("Error during executor shutdown", e);
271 }
272
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700273 deviceDescs.clear();
274 devices.clear();
275 devicePorts.clear();
276 availableDevices.clear();
Jonathan Hart46ab5cc2016-09-15 15:42:39 -0700277 clusterCommunicator.removeSubscriber(DEVICE_UPDATE);
278 clusterCommunicator.removeSubscriber(DEVICE_OFFLINE);
279 clusterCommunicator.removeSubscriber(DEVICE_REMOVE_REQ);
280 clusterCommunicator.removeSubscriber(DEVICE_REMOVED);
281 clusterCommunicator.removeSubscriber(PORT_UPDATE);
282 clusterCommunicator.removeSubscriber(PORT_STATUS_UPDATE);
283 clusterCommunicator.removeSubscriber(DEVICE_ADVERTISE);
284 clusterCommunicator.removeSubscriber(DEVICE_INJECTED);
285 clusterCommunicator.removeSubscriber(PORT_INJECTED);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700286 log.info("Stopped");
287 }
288
289 @Override
290 public int getDeviceCount() {
291 return devices.size();
292 }
293
294 @Override
295 public Iterable<Device> getDevices() {
296 return Collections.unmodifiableCollection(devices.values());
297 }
298
299 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800300 public Iterable<Device> getAvailableDevices() {
301 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700302 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800303 }
304
305 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700306 public Device getDevice(DeviceId deviceId) {
307 return devices.get(deviceId);
308 }
309
310 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700311 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700312 DeviceId deviceId,
313 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800314 NodeId localNode = clusterService.getLocalNode().id();
315 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
316
317 // Process device update only if we're the master,
318 // otherwise signal the actual master.
319 DeviceEvent deviceEvent = null;
320 if (localNode.equals(deviceNode)) {
321
322 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
323 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
324 final Timestamped<DeviceDescription> mergedDesc;
325 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
326
327 synchronized (device) {
328 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
329 mergedDesc = device.get(providerId).getDeviceDesc();
330 }
331
332 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700333 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
helenyrwufd296b62016-06-22 17:43:02 -0700334 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800335 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
336 }
337
338 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800339 // Only forward for ConfigProvider
340 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800341 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800342 return null;
343 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800344 // FIXME Temporary hack for NPE (ONOS-1171).
345 // Proper fix is to implement forwarding to master on ConfigProvider
346 // redo ONOS-490
347 if (deviceNode == null) {
348 // silently ignore
349 return null;
350 }
351
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800352
353 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
354 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800355
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800356 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700357 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800358 /* error log:
359 log.warn("Failed to process injected device id: {} desc: {} " +
360 "(cluster messaging failed: {})",
361 deviceId, deviceDescription, e);
362 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700363 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800364
365 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700366 }
367
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700368 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700369 DeviceId deviceId,
370 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700371
372 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800373 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700374 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700375
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800376 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700377 // locking per device
378
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700379 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
380 log.debug("Ignoring outdated event: {}", deltaDesc);
381 return null;
382 }
383
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800384 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700385
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700386 final Device oldDevice = devices.get(deviceId);
387 final Device newDevice;
388
389 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700390 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700391 // on new device or valid update
392 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800393 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700394 } else {
395 // outdated event, ignored.
396 return null;
397 }
398 if (oldDevice == null) {
helenyrwufd296b62016-06-22 17:43:02 -0700399 // REGISTER
400 if (!deltaDesc.value().isDefaultAvailable()) {
Jordan Halterman47076dd2017-04-19 07:55:48 -0700401 return registerDevice(providerId, newDevice, deltaDesc.timestamp());
helenyrwufd296b62016-06-22 17:43:02 -0700402 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700403 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700404 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700405 } else {
406 // UPDATE or ignore (no change or stale)
helenyrwufd296b62016-06-22 17:43:02 -0700407 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp(),
408 deltaDesc.value().isDefaultAvailable());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700409 }
410 }
411 }
412
413 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700414 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700415 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700416 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700417
418 // update composed device cache
419 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
420 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700421 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
422 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700423
424 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700425 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700426 }
427
428 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
429 }
430
431 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700432 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700433 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700434 Device oldDevice,
helenyrwufd296b62016-06-22 17:43:02 -0700435 Device newDevice, Timestamp newTimestamp,
436 boolean forceAvailable) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700437 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700438 boolean propertiesChanged =
439 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700440 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
441 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700442 boolean annotationsChanged =
443 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700444
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700445 // Primary providers can respond to all changes, but ancillary ones
446 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800447 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700448 if ((providerId.isAncillary() && annotationsChanged) ||
449 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700450 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
451 if (!replaced) {
452 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700453 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800454 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700455 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700456
alshabibdc5d8bd2015-11-02 15:41:29 -0800457 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700458 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800459
helenyrwufd296b62016-06-22 17:43:02 -0700460 if (!providerId.isAncillary() && forceAvailable) {
alshabibdc5d8bd2015-11-02 15:41:29 -0800461 boolean wasOnline = availableDevices.contains(newDevice.id());
462 markOnline(newDevice.id(), newTimestamp);
463 if (!wasOnline) {
464 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
465 }
466 }
467 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700468 }
469
Jordan Halterman47076dd2017-04-19 07:55:48 -0700470 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice, Timestamp newTimestamp) {
helenyrwufd296b62016-06-22 17:43:02 -0700471 // update composed device cache
472 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
473 verify(oldDevice == null,
474 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
475 providerId, oldDevice, newDevice);
476
477 if (!providerId.isAncillary()) {
Jordan Halterman47076dd2017-04-19 07:55:48 -0700478 markOffline(newDevice.id(), newTimestamp);
helenyrwufd296b62016-06-22 17:43:02 -0700479 }
480
481 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
482 }
483
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700484 @Override
485 public DeviceEvent markOffline(DeviceId deviceId) {
Jordan Halterman47076dd2017-04-19 07:55:48 -0700486 return markOffline(deviceId, deviceClockService.getTimestamp(deviceId));
487 }
488
489 private DeviceEvent markOffline(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700490 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700491 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700492 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700493 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800494 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700495 }
496 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700497 }
498
499 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700500 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700501 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700502
503 // locking device
504 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700505 // accept off-line if given timestamp is newer than
506 // the latest Timestamp from Primary provider
507 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
Thomas Vachuska4bd10b92016-12-15 10:13:38 -0800508 if (primDescs == null) {
509 return null;
510 }
511
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700512 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
513 if (timestamp.compareTo(lastTimestamp) <= 0) {
514 // outdated event ignore
515 return null;
516 }
517
518 offline.put(deviceId, timestamp);
519
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700520 Device device = devices.get(deviceId);
521 if (device == null) {
522 return null;
523 }
524 boolean removed = availableDevices.remove(deviceId);
525 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700526 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700527 }
528 return null;
529 }
530 }
531
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700532 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700533 public boolean markOnline(DeviceId deviceId) {
534 if (devices.containsKey(deviceId)) {
535 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
536 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
537 synchronized (deviceLock) {
538 if (markOnline(deviceId, timestamp)) {
539 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
540 return true;
541 } else {
542 return false;
543 }
544 }
545 }
546 log.warn("Device {} does not exist in store", deviceId);
547 return false;
548
549 }
550
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700551 /**
552 * Marks the device as available if the given timestamp is not outdated,
553 * compared to the time the device has been marked offline.
554 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700555 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700556 * @param timestamp of the event triggering this change.
557 * @return true if availability change request was accepted and changed the state
558 */
559 // Guarded by deviceDescs value (=Device lock)
560 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
561 // accept on-line if given timestamp is newer than
562 // the latest offline request Timestamp
563 Timestamp offlineTimestamp = offline.get(deviceId);
564 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700565 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700566
567 offline.remove(deviceId);
568 return availableDevices.add(deviceId);
569 }
570 return false;
571 }
572
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700573 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700574 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700575 DeviceId deviceId,
576 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700577
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800578 NodeId localNode = clusterService.getLocalNode().id();
579 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
580 // since it will trigger distributed store read.
581 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
582 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
583 // If we don't care much about topology performance, then it might be OK.
584 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700585
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800586 // Process port update only if we're the master of the device,
587 // otherwise signal the actual master.
588 List<DeviceEvent> deviceEvents = null;
589 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700590
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800591 final Timestamp newTimestamp;
592 try {
593 newTimestamp = deviceClockService.getTimestamp(deviceId);
594 } catch (IllegalStateException e) {
595 log.info("Timestamp was not available for device {}", deviceId);
596 log.debug(" discarding {}", portDescriptions);
597 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700598
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800599 // Possible situation:
600 // Device connected and became master for short period of time,
601 // but lost mastership before this instance had the chance to
602 // retrieve term information.
603
604 // Information dropped here is expected to be recoverable by
605 // device probing after mastership change
606
607 return Collections.emptyList();
608 }
609 log.debug("timestamp for {} {}", deviceId, newTimestamp);
610
611 final Timestamped<List<PortDescription>> timestampedInput
612 = new Timestamped<>(portDescriptions, newTimestamp);
613 final Timestamped<List<PortDescription>> merged;
614
615 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
616
617 synchronized (device) {
618 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
619 final DeviceDescriptions descs = device.get(providerId);
620 List<PortDescription> mergedList =
621 FluentIterable.from(portDescriptions)
Thomas Vachuska0a669b22017-02-14 10:45:52 -0800622 .filter(input -> input.portNumber() != null)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700623 .transform(input ->
624 // lookup merged port description
625 descs.getPortDesc(input.portNumber()).value()
626 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700627 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800628 }
629
630 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700631 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700632 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800633 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
634 }
635
636 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800637 // Only forward for ConfigProvider
638 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800639 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta89461772016-01-26 12:18:10 -0800640 return Collections.emptyList();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800641 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800642 // FIXME Temporary hack for NPE (ONOS-1171).
643 // Proper fix is to implement forwarding to master on ConfigProvider
644 // redo ONOS-490
645 if (deviceNode == null) {
646 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800647 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800648 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800649
650 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800651
652 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700653 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800654 /* error log:
655 log.warn("Failed to process injected ports of device id: {} " +
656 "(cluster messaging failed: {})",
657 deviceId, e);
658 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700659 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700660
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800661 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700662 }
663
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700664 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700665 DeviceId deviceId,
666 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700667
668 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700669 if (device == null) {
670 log.debug("Device is no longer valid: {}", deviceId);
671 return Collections.emptyList();
672 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700673
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700674 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700675 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
676
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700677 List<DeviceEvent> events = new ArrayList<>();
678 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700679
680 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
681 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700682 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700683 }
684
685 DeviceDescriptions descs = descsMap.get(providerId);
686 // every provider must provide DeviceDescription.
687 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700688 "Device description for Device ID %s from Provider %s was not found",
689 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700690
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700691 Map<PortNumber, Port> ports = getPortMap(deviceId);
692
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700693 final Timestamp newTimestamp = portDescriptions.timestamp();
694
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700695 // Add new ports
696 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700697 for (PortDescription portDescription : portDescriptions.value()) {
698 final PortNumber number = portDescription.portNumber();
699 processed.add(number);
700
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700701 final Port oldPort = ports.get(number);
702 final Port newPort;
703
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700704
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700705 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
706 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700707 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700708 // on new port or valid update
709 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700710 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700711 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700712 newPort = composePort(device, number, descsMap);
713 } else {
714 // outdated event, ignored.
715 continue;
716 }
717
718 events.add(oldPort == null ?
719 createPort(device, newPort, ports) :
720 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700721 }
722
723 events.addAll(pruneOldPorts(device, ports, processed));
724 }
725 return FluentIterable.from(events).filter(notNull()).toList();
726 }
727
728 // Creates a new port based on the port description adds it to the map and
729 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700730 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700731 private DeviceEvent createPort(Device device, Port newPort,
732 Map<PortNumber, Port> ports) {
733 ports.put(newPort.number(), newPort);
734 return new DeviceEvent(PORT_ADDED, device, newPort);
735 }
736
737 // Checks if the specified port requires update and if so, it replaces the
738 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700739 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700740 private DeviceEvent updatePort(Device device, Port oldPort,
741 Port newPort,
742 Map<PortNumber, Port> ports) {
Michal Mach31097ad2017-01-25 11:02:55 +0100743
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700744 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700745 oldPort.type() != newPort.type() ||
746 oldPort.portSpeed() != newPort.portSpeed() ||
747 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700748 ports.put(oldPort.number(), newPort);
749 return new DeviceEvent(PORT_UPDATED, device, newPort);
750 }
751 return null;
752 }
753
Michal Mach31097ad2017-01-25 11:02:55 +0100754 private DeviceEvent removePort(DeviceId deviceId, PortNumber portNumber) {
755
756 log.info("Deleted port: " + deviceId.toString() + "/" + portNumber.toString());
757 Port deletedPort = devicePorts.get(deviceId).remove(portNumber);
758
759 return new DeviceEvent(PORT_REMOVED, getDevice(deviceId), deletedPort);
760 }
761
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700762 // Prunes the specified list of ports based on which ports are in the
763 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700764 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700765 private List<DeviceEvent> pruneOldPorts(Device device,
766 Map<PortNumber, Port> ports,
767 Set<PortNumber> processed) {
768 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700769 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700770 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700771 Entry<PortNumber, Port> e = iterator.next();
772 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700773 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700774 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700775 iterator.remove();
776 }
777 }
778 return events;
779 }
780
781 // Gets the map of ports for the specified device; if one does not already
782 // exist, it creates and registers a new one.
783 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700784 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700785 }
786
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700787 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700788 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700789 Map<ProviderId, DeviceDescriptions> r;
790 r = deviceDescs.get(deviceId);
791 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700792 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700793 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
794 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
795 if (concurrentlyAdded != null) {
796 r = concurrentlyAdded;
797 }
798 }
799 return r;
800 }
801
802 // Guarded by deviceDescs value (=Device lock)
803 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
804 Map<ProviderId, DeviceDescriptions> device,
805 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700806 synchronized (device) {
807 DeviceDescriptions r = device.get(providerId);
808 if (r == null) {
809 r = new DeviceDescriptions(deltaDesc);
810 device.put(providerId, r);
811 }
812 return r;
813 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700814 }
815
816 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700817 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
818 DeviceId deviceId,
819 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700820 final Timestamp newTimestamp;
821 try {
822 newTimestamp = deviceClockService.getTimestamp(deviceId);
823 } catch (IllegalStateException e) {
824 log.info("Timestamp was not available for device {}", deviceId);
825 log.debug(" discarding {}", portDescription);
826 // Failed to generate timestamp. Ignoring.
827 // See updatePorts comment
828 return null;
829 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700830 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700831 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700832 final DeviceEvent event;
833 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800834 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
835 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700836 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800837 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700838 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700839 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700840 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700841 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700842 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800843 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700844 }
845 return event;
846 }
847
848 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700849 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700850 Device device = devices.get(deviceId);
851 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
852
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700853 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700854 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
855
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700856 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700857
858 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
859 log.debug("Ignoring outdated event: {}", deltaDesc);
860 return null;
861 }
862
863 DeviceDescriptions descs = descsMap.get(providerId);
864 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700865 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700866 "Device description for Device ID %s from Provider %s was not found",
867 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700868
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700869 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
870 final PortNumber number = deltaDesc.value().portNumber();
871 final Port oldPort = ports.get(number);
872 final Port newPort;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700873 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
Michal Mach31097ad2017-01-25 11:02:55 +0100874 boolean toDelete = false;
875
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700876 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);
Michal Mach31097ad2017-01-25 11:02:55 +0100882 toDelete = deltaDesc.value().isRemoved();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700883 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700884 // same or outdated event, ignored.
885 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700886 return null;
887 }
888
889 if (oldPort == null) {
890 return createPort(device, newPort, ports);
891 } else {
Michal Mach31097ad2017-01-25 11:02:55 +0100892 return toDelete ? removePort(deviceId, number) : updatePort(device, oldPort, newPort, ports);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700893 }
894 }
895 }
896
897 @Override
898 public List<Port> getPorts(DeviceId deviceId) {
899 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
900 if (ports == null) {
901 return Collections.emptyList();
902 }
903 return ImmutableList.copyOf(ports.values());
904 }
905
906 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700907 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
908 DeviceId deviceId) {
909 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
910 if (descs == null) {
911 return null;
912 }
913 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
914 final Optional<DeviceDescriptions> devDescs;
915 synchronized (descs) {
916 devDescs = Optional.ofNullable(descs.get(pid));
917 }
918 // DeviceDescriptions is concurrent access-safe
919 return devDescs
920 .map(dd -> dd.getPortDescs().values().stream()
921 .map(Timestamped::value))
922 .orElse(Stream.empty());
923 }
924
925 @Override
sangho538108b2015-04-08 14:29:20 -0700926 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200927 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700928
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200929 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
930 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
931 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
932
933 if (prvStatsMap != null) {
934 for (PortStatistics newStats : newStatsCollection) {
935 PortNumber port = PortNumber.portNumber(newStats.port());
936 PortStatistics prvStats = prvStatsMap.get(port);
937 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
938 PortStatistics deltaStats = builder.build();
939 if (prvStats != null) {
940 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
941 }
942 deltaStatsMap.put(port, deltaStats);
943 newStatsMap.put(port, newStats);
944 }
945 } else {
946 for (PortStatistics newStats : newStatsCollection) {
947 PortNumber port = PortNumber.portNumber(newStats.port());
948 newStatsMap.put(port, newStats);
949 }
sangho538108b2015-04-08 14:29:20 -0700950 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200951 devicePortDeltaStats.put(deviceId, deltaStatsMap);
952 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200953 // DeviceEvent returns null because of InternalPortStatsListener usage
954 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200955 }
956
957 /**
958 * Calculate delta statistics by subtracting previous from new statistics.
959 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700960 * @param deviceId device identifier
961 * @param prvStats previous port statistics
962 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200963 * @return PortStatistics
964 */
965 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
966 // calculate time difference
967 long deltaStatsSec, deltaStatsNano;
968 if (newStats.durationNano() < prvStats.durationNano()) {
969 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
970 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
971 } else {
972 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
973 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
974 }
975 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
976 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
977 .setPort(newStats.port())
978 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
979 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
980 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
981 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
982 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
983 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
984 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
985 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
986 .setDurationSec(deltaStatsSec)
987 .setDurationNano(deltaStatsNano)
988 .build();
989 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700990 }
991
992 @Override
993 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700994 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
995 if (portStats == null) {
996 return Collections.emptyList();
997 }
998 return ImmutableList.copyOf(portStats.values());
999 }
1000
1001 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +05301002 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
1003 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
1004 if (portStatsMap == null) {
1005 return null;
1006 }
1007 PortStatistics portStats = portStatsMap.get(portNumber);
1008 return portStats;
1009 }
1010
1011 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001012 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
1013 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
1014 if (portStats == null) {
1015 return Collections.emptyList();
1016 }
1017 return ImmutableList.copyOf(portStats.values());
1018 }
1019
1020 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +05301021 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
1022 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
1023 if (portStatsMap == null) {
1024 return null;
1025 }
1026 PortStatistics portStats = portStatsMap.get(portNumber);
1027 return portStats;
1028 }
1029
1030 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001031 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
1032 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1033 return ports == null ? null : ports.get(portNumber);
1034 }
1035
1036 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -07001037 public PortDescription getPortDescription(ProviderId pid,
1038 DeviceId deviceId,
1039 PortNumber portNumber) {
1040 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1041 if (descs == null) {
1042 return null;
1043 }
1044 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1045 final Optional<DeviceDescriptions> devDescs;
1046 synchronized (descs) {
1047 devDescs = Optional.ofNullable(descs.get(pid));
1048 }
1049 // DeviceDescriptions is concurrent access-safe
1050 return devDescs
1051 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1052 .map(Timestamped::value)
1053 .orElse(null);
1054 }
1055
1056 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001057 public boolean isAvailable(DeviceId deviceId) {
1058 return availableDevices.contains(deviceId);
1059 }
1060
1061 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001062 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001063 final NodeId myId = clusterService.getLocalNode().id();
1064 NodeId master = mastershipService.getMasterFor(deviceId);
1065
1066 // if there exist a master, forward
1067 // if there is no master, try to become one and process
1068
1069 boolean relinquishAtEnd = false;
1070 if (master == null) {
1071 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1072 if (myRole != MastershipRole.NONE) {
1073 relinquishAtEnd = true;
1074 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001075 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001076 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001077 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -07001078 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001079 master = myId;
1080 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001081 }
1082
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001083 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001084 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001085 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001086
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001087 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001088 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001089 /* error log:
1090 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1091 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001092
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001093 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001094 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001095 }
1096
1097 // I have control..
1098
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -07001099 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001100 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001101 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001102 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001103 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001104 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001105 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001106 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001107 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001108 mastershipService.relinquishMastership(deviceId);
1109 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001110 return event;
1111 }
1112
1113 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
1114 Timestamp timestamp) {
1115
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001116 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001117 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001118 // accept removal request if given timestamp is newer than
1119 // the latest Timestamp from Primary provider
1120 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001121 if (primDescs == null) {
1122 return null;
1123 }
1124
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001125 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
1126 if (timestamp.compareTo(lastTimestamp) <= 0) {
1127 // outdated event ignore
1128 return null;
1129 }
1130 removalRequest.put(deviceId, timestamp);
1131
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001132 Device device = devices.remove(deviceId);
1133 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001134 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1135 if (ports != null) {
1136 ports.clear();
1137 }
1138 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001139 descs.clear();
1140 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001141 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001142 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001143 }
1144
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001145 /**
1146 * Checks if given timestamp is superseded by removal request
1147 * with more recent timestamp.
1148 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001149 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001150 * @param timestampToCheck timestamp of an event to check
1151 * @return true if device is already removed
1152 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001153 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1154 Timestamp removalTimestamp = removalRequest.get(deviceId);
1155 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001156 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001157 // removalRequest is more recent
1158 return true;
1159 }
1160 return false;
1161 }
1162
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001163 /**
1164 * Returns a Device, merging description given from multiple Providers.
1165 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001166 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001167 * @param providerDescs Collection of Descriptions from multiple providers
1168 * @return Device instance
1169 */
1170 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001171 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001172
Thomas Vachuska444eda62014-10-28 13:09:42 -07001173 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001174
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001175 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001176
1177 DeviceDescriptions desc = providerDescs.get(primary);
1178
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001179 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001180 Type type = base.type();
1181 String manufacturer = base.manufacturer();
1182 String hwVersion = base.hwVersion();
1183 String swVersion = base.swVersion();
1184 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001185 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001186 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1187 annotations = merge(annotations, base.annotations());
1188
1189 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1190 if (e.getKey().equals(primary)) {
1191 continue;
1192 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001193 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001194 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001195 // Currently assuming there will never be a key conflict between
1196 // providers
1197
1198 // annotation merging. not so efficient, should revisit later
1199 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1200 }
1201
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001202 return new DefaultDevice(primary, deviceId, type, manufacturer,
1203 hwVersion, swVersion, serialNumber,
1204 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001205 }
1206
Marc De Leenheer88194c32015-05-29 22:10:59 -07001207 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1208 PortDescription description, Annotations annotations) {
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001209 // FIXME this switch need to go away once all ports are done.
Marc De Leenheer88194c32015-05-29 22:10:59 -07001210 switch (description.type()) {
1211 case OMS:
HIGUCHI Yuta95d83e82016-04-26 12:13:48 -07001212 if (description instanceof OmsPortDescription) {
1213 // remove if-block once deprecation is complete
1214 OmsPortDescription omsDesc = (OmsPortDescription) description;
1215 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1216 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1217 }
1218 // same as default
1219 return new DefaultPort(device, number, isEnabled, description.type(),
1220 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001221 case OCH:
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001222 if (description instanceof OchPortDescription) {
1223 // remove if-block once Och deprecation is complete
1224 OchPortDescription ochDesc = (OchPortDescription) description;
1225 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1226 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1227 }
1228 return new DefaultPort(device, number, isEnabled, description.type(),
1229 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001230 case ODUCLT:
HIGUCHI Yuta4c0ef6b2016-05-02 19:45:41 -07001231 if (description instanceof OduCltPortDescription) {
1232 // remove if-block once deprecation is complete
1233 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1234 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1235 }
1236 // same as default
1237 return new DefaultPort(device, number, isEnabled, description.type(),
1238 description.portSpeed(), annotations);
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +02001239 case OTU:
HIGUCHI Yuta5be3e822016-05-03 13:51:42 -07001240 if (description instanceof OtuPortDescription) {
1241 // remove if-block once deprecation is complete
1242 OtuPortDescription otuDesc = (OtuPortDescription) description;
1243 return new OtuPort(device, number, isEnabled, otuDesc.signalType(), annotations);
1244 }
1245 // same as default
1246 return new DefaultPort(device, number, isEnabled, description.type(),
1247 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001248 default:
1249 return new DefaultPort(device, number, isEnabled, description.type(),
1250 description.portSpeed(), annotations);
1251 }
1252 }
1253
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001254 /**
1255 * Returns a Port, merging description given from multiple Providers.
1256 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001257 * @param device device the port is on
1258 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001259 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001260 * @return Port instance
1261 */
1262 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001263 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001264
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001265 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001266 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001267 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001268 boolean isEnabled = false;
1269 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001270 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001271 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1272 if (portDesc != null) {
1273 isEnabled = portDesc.value().isEnabled();
1274 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001275 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001276 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001277 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001278 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001279 if (e.getKey().equals(primary)) {
1280 continue;
1281 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001282 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001283 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001284 // Currently assuming there will never be a key conflict between
1285 // providers
1286
1287 // annotation merging. not so efficient, should revisit later
1288 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1289 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001290 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1291 continue;
1292 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001293 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001294 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001295 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001296 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001297 }
1298 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001299 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001300 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001301 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001302 PortDescription current = portDesc.value();
1303 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001304 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001305 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001306 }
1307
1308 /**
1309 * @return primary ProviderID, or randomly chosen one if none exists
1310 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001311 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001312 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001313 ProviderId fallBackPrimary = null;
1314 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1315 if (!e.getKey().isAncillary()) {
1316 return e.getKey();
1317 } else if (fallBackPrimary == null) {
1318 // pick randomly as a fallback in case there is no primary
1319 fallBackPrimary = e.getKey();
1320 }
1321 }
1322 return fallBackPrimary;
1323 }
1324
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001325 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001326 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001327 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001328 return providerDescs.get(pid);
1329 }
1330
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001331 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001332 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001333 }
1334
Jonathan Hart7d656f42015-01-27 14:07:23 -08001335 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001336 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001337 }
Madan Jampani47c93732014-10-06 20:46:08 -07001338
Jonathan Hart7d656f42015-01-27 14:07:23 -08001339 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001340 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001341 }
1342
Jonathan Hart7d656f42015-01-27 14:07:23 -08001343 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001344 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001345 }
1346
Jonathan Hart7d656f42015-01-27 14:07:23 -08001347 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001348 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001349 }
1350
Jonathan Hart7d656f42015-01-27 14:07:23 -08001351 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001352 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001353 }
1354
Jonathan Hart7d656f42015-01-27 14:07:23 -08001355 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001356 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1357 }
1358
1359 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1360 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001361 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001362 } catch (IOException e) {
1363 log.error("Failed to send" + event + " to " + recipient, e);
1364 }
1365 }
1366
1367 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1368 try {
1369 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1370 } catch (IOException e) {
1371 log.error("Failed to send" + event + " to " + recipient, e);
1372 }
1373 }
1374
1375 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1376 try {
1377 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1378 } catch (IOException e) {
1379 log.error("Failed to send" + event + " to " + recipient, e);
1380 }
1381 }
1382
1383 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1384 try {
1385 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1386 } catch (IOException e) {
1387 log.error("Failed to send" + event + " to " + recipient, e);
1388 }
1389 }
1390
1391 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1392 try {
1393 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1394 } catch (IOException e) {
1395 log.error("Failed to send" + event + " to " + recipient, e);
1396 }
1397 }
1398
1399 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1400 final NodeId self = clusterService.getLocalNode().id();
1401
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001402 final int numDevices = deviceDescs.size();
1403 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1404 final int portsPerDevice = 8; // random factor to minimize reallocation
1405 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1406 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001407
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001408 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001409
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001410 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001411 synchronized (devDescs) {
1412
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001413 // send device offline timestamp
1414 Timestamp lOffline = this.offline.get(deviceId);
1415 if (lOffline != null) {
1416 adOffline.put(deviceId, lOffline);
1417 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001418
1419 for (Entry<ProviderId, DeviceDescriptions>
1420 prov : devDescs.entrySet()) {
1421
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001422 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001423 final ProviderId provId = prov.getKey();
1424 final DeviceDescriptions descs = prov.getValue();
1425
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001426 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001427 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001428
1429 for (Entry<PortNumber, Timestamped<PortDescription>>
1430 portDesc : descs.getPortDescs().entrySet()) {
1431
1432 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001433 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001434 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001435 }
1436 }
1437 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001438 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001439
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001440 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001441 }
1442
1443 /**
1444 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001445 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001446 * Notify sender about out-dated information using regular replication message.
1447 * Send back advertisement to sender if not in sync.
1448 *
1449 * @param advertisement to respond to
1450 */
1451 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1452
1453 final NodeId sender = advertisement.sender();
1454
1455 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1456 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1457 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1458
1459 // Fragments to request
1460 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1461 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1462
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001463 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001464 final DeviceId deviceId = de.getKey();
1465 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1466
1467 synchronized (lDevice) {
1468 // latestTimestamp across provider
1469 // Note: can be null initially
1470 Timestamp localLatest = offline.get(deviceId);
1471
1472 // handle device Ads
1473 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1474 final ProviderId provId = prov.getKey();
1475 final DeviceDescriptions lDeviceDescs = prov.getValue();
1476
1477 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1478
1479
1480 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1481 Timestamp advDevTimestamp = devAds.get(devFragId);
1482
Jonathan Hart403ea932015-02-20 16:23:00 -08001483 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1484 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001485 // remote does not have it or outdated, suggest
1486 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1487 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1488 // local is outdated, request
1489 reqDevices.add(devFragId);
1490 }
1491
1492 // handle port Ads
1493 for (Entry<PortNumber, Timestamped<PortDescription>>
1494 pe : lDeviceDescs.getPortDescs().entrySet()) {
1495
1496 final PortNumber num = pe.getKey();
1497 final Timestamped<PortDescription> lPort = pe.getValue();
1498
1499 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1500
1501 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001502 if (advPortTimestamp == null || lPort.isNewerThan(
1503 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001504 // remote does not have it or outdated, suggest
1505 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1506 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1507 // local is outdated, request
1508 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1509 reqPorts.add(portFragId);
1510 }
1511
1512 // remove port Ad already processed
1513 portAds.remove(portFragId);
1514 } // end local port loop
1515
1516 // remove device Ad already processed
1517 devAds.remove(devFragId);
1518
1519 // find latest and update
1520 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1521 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001522 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001523 localLatest = providerLatest;
1524 }
1525 } // end local provider loop
1526
1527 // checking if remote timestamp is more recent.
1528 Timestamp rOffline = offlineAds.get(deviceId);
1529 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001530 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001531 // remote offline timestamp suggests that the
1532 // device is off-line
1533 markOfflineInternal(deviceId, rOffline);
1534 }
1535
1536 Timestamp lOffline = offline.get(deviceId);
1537 if (lOffline != null && rOffline == null) {
1538 // locally offline, but remote is online, suggest offline
1539 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1540 }
1541
1542 // remove device offline Ad already processed
1543 offlineAds.remove(deviceId);
1544 } // end local device loop
1545 } // device lock
1546
1547 // If there is any Ads left, request them
1548 log.trace("Ads left {}, {}", devAds, portAds);
1549 reqDevices.addAll(devAds.keySet());
1550 reqPorts.addAll(portAds.keySet());
1551
1552 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1553 log.trace("Nothing to request to remote peer {}", sender);
1554 return;
1555 }
1556
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001557 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001558
1559 // 2-way Anti-Entropy for now
1560 try {
1561 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1562 } catch (IOException e) {
1563 log.error("Failed to send response advertisement to " + sender, e);
1564 }
1565
1566// Sketch of 3-way Anti-Entropy
1567// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1568// ClusterMessage message = new ClusterMessage(
1569// clusterService.getLocalNode().id(),
1570// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1571// SERIALIZER.encode(request));
1572//
1573// try {
1574// clusterCommunicator.unicast(message, advertisement.sender());
1575// } catch (IOException e) {
1576// log.error("Failed to send advertisement reply to "
1577// + advertisement.sender(), e);
1578// }
Madan Jampani47c93732014-10-06 20:46:08 -07001579 }
1580
Madan Jampani255a58b2014-10-09 12:08:20 -07001581 private void notifyDelegateIfNotNull(DeviceEvent event) {
1582 if (event != null) {
1583 notifyDelegate(event);
1584 }
1585 }
1586
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001587 private final class SendAdvertisementTask implements Runnable {
1588
1589 @Override
1590 public void run() {
1591 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001592 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001593 return;
1594 }
1595
1596 try {
1597 final NodeId self = clusterService.getLocalNode().id();
1598 Set<ControllerNode> nodes = clusterService.getNodes();
1599
1600 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1601 .transform(toNodeId())
1602 .toList();
1603
1604 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001605 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001606 return;
1607 }
1608
1609 NodeId peer;
1610 do {
1611 int idx = RandomUtils.nextInt(0, nodeIds.size());
1612 peer = nodeIds.get(idx);
1613 } while (peer.equals(self));
1614
1615 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1616
1617 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001618 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001619 return;
1620 }
1621
1622 try {
1623 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1624 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001625 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001626 return;
1627 }
1628 } catch (Exception e) {
1629 // catch all Exception to avoid Scheduled task being suppressed.
1630 log.error("Exception thrown while sending advertisement", e);
1631 }
1632 }
1633 }
1634
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001635 private void handleDeviceEvent(InternalDeviceEvent event) {
1636 ProviderId providerId = event.providerId();
1637 DeviceId deviceId = event.deviceId();
1638 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001639
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001640 try {
1641 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1642 deviceDescription));
1643 } catch (Exception e) {
1644 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001645 }
1646 }
1647
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001648 private void handleDeviceOfflineEvent(InternalDeviceOfflineEvent event) {
1649 DeviceId deviceId = event.deviceId();
1650 Timestamp timestamp = event.timestamp();
Madan Jampani25322532014-10-08 11:20:38 -07001651
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001652 try {
1653 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1654 } catch (Exception e) {
1655 log.warn("Exception thrown handling device offline", e);
Madan Jampani25322532014-10-08 11:20:38 -07001656 }
1657 }
1658
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001659 private void handleRemoveRequest(DeviceId did) {
1660 try {
Jayasree Ghosha2a3cc62017-02-27 18:35:32 +05301661 DeviceEvent event = removeDevice(did);
1662 notifyDelegateIfNotNull(event);
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001663 } catch (Exception e) {
1664 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001665 }
1666 }
1667
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001668 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1669 DeviceId deviceId = event.deviceId();
1670 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001671
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001672 try {
1673 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1674 } catch (Exception e) {
1675 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001676 }
1677 }
1678
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001679 private void handlePortEvent(InternalPortEvent event) {
1680 ProviderId providerId = event.providerId();
1681 DeviceId deviceId = event.deviceId();
1682 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001683
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001684 if (getDevice(deviceId) == null) {
1685 log.debug("{} not found on this node yet, ignoring.", deviceId);
1686 // Note: dropped information will be recovered by anti-entropy
1687 return;
1688 }
Madan Jampani47c93732014-10-06 20:46:08 -07001689
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001690 try {
1691 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1692 } catch (Exception e) {
1693 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001694 }
1695 }
1696
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001697 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1698 ProviderId providerId = event.providerId();
1699 DeviceId deviceId = event.deviceId();
1700 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001701
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001702 if (getDevice(deviceId) == null) {
1703 log.debug("{} not found on this node yet, ignoring.", deviceId);
1704 // Note: dropped information will be recovered by anti-entropy
1705 return;
1706 }
Madan Jampani47c93732014-10-06 20:46:08 -07001707
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001708 try {
1709 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1710 } catch (Exception e) {
1711 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001712 }
1713 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001714
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001715 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1716 try {
1717 handleAdvertisement(advertisement);
1718 } catch (Exception e) {
1719 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001720 }
1721 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001722
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001723 private void handleDeviceInjectedEvent(DeviceInjectedEvent event) {
1724 ProviderId providerId = event.providerId();
1725 DeviceId deviceId = event.deviceId();
1726 DeviceDescription deviceDescription = event.deviceDescription();
1727 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1728 // workaround for ONOS-1208
1729 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1730 return;
1731 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001732
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001733 try {
1734 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1735 } catch (Exception e) {
1736 log.warn("Exception thrown handling device injected event.", e);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001737 }
1738 }
1739
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001740 private void handlePortInjectedEvent(PortInjectedEvent event) {
1741 ProviderId providerId = event.providerId();
1742 DeviceId deviceId = event.deviceId();
1743 List<PortDescription> portDescriptions = event.portDescriptions();
1744 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1745 // workaround for ONOS-1208
1746 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1747 return;
1748 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001749
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001750 try {
1751 updatePorts(providerId, deviceId, portDescriptions);
1752 } catch (Exception e) {
1753 log.warn("Exception thrown handling port injected event.", e);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001754 }
1755 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001756
1757 private class InternalPortStatsListener
1758 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1759 @Override
1760 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1761 if (event.type() == PUT) {
1762 Device device = devices.get(event.key());
1763 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001764 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001765 }
1766 }
1767 }
1768 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001769}