blob: 4e6c05d205b83887cfc3b235ac20f99b91f6650c [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()) {
401 return registerDevice(providerId, newDevice);
402 }
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
helenyrwufd296b62016-06-22 17:43:02 -0700470 private DeviceEvent registerDevice(ProviderId providerId, Device newDevice) {
471 // 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()) {
478 markOffline(newDevice.id());
479 }
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) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700486 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700487 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700488 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700489 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700490 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800491 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700492 }
493 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700494 }
495
496 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700497 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700498 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700499
500 // locking device
501 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700502 // accept off-line if given timestamp is newer than
503 // the latest Timestamp from Primary provider
504 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
Thomas Vachuska4bd10b92016-12-15 10:13:38 -0800505 if (primDescs == null) {
506 return null;
507 }
508
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700509 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
510 if (timestamp.compareTo(lastTimestamp) <= 0) {
511 // outdated event ignore
512 return null;
513 }
514
515 offline.put(deviceId, timestamp);
516
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700517 Device device = devices.get(deviceId);
518 if (device == null) {
519 return null;
520 }
521 boolean removed = availableDevices.remove(deviceId);
522 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700523 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700524 }
525 return null;
526 }
527 }
528
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700529 @Override
helenyrwufd296b62016-06-22 17:43:02 -0700530 public boolean markOnline(DeviceId deviceId) {
531 if (devices.containsKey(deviceId)) {
532 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
533 Map<?, ?> deviceLock = getOrCreateDeviceDescriptionsMap(deviceId);
534 synchronized (deviceLock) {
535 if (markOnline(deviceId, timestamp)) {
536 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, getDevice(deviceId), null));
537 return true;
538 } else {
539 return false;
540 }
541 }
542 }
543 log.warn("Device {} does not exist in store", deviceId);
544 return false;
545
546 }
547
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700548 /**
549 * Marks the device as available if the given timestamp is not outdated,
550 * compared to the time the device has been marked offline.
551 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700552 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700553 * @param timestamp of the event triggering this change.
554 * @return true if availability change request was accepted and changed the state
555 */
556 // Guarded by deviceDescs value (=Device lock)
557 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
558 // accept on-line if given timestamp is newer than
559 // the latest offline request Timestamp
560 Timestamp offlineTimestamp = offline.get(deviceId);
561 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700562 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700563
564 offline.remove(deviceId);
565 return availableDevices.add(deviceId);
566 }
567 return false;
568 }
569
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700570 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700571 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700572 DeviceId deviceId,
573 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700574
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800575 NodeId localNode = clusterService.getLocalNode().id();
576 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
577 // since it will trigger distributed store read.
578 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
579 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
580 // If we don't care much about topology performance, then it might be OK.
581 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700582
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800583 // Process port update only if we're the master of the device,
584 // otherwise signal the actual master.
585 List<DeviceEvent> deviceEvents = null;
586 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700587
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800588 final Timestamp newTimestamp;
589 try {
590 newTimestamp = deviceClockService.getTimestamp(deviceId);
591 } catch (IllegalStateException e) {
592 log.info("Timestamp was not available for device {}", deviceId);
593 log.debug(" discarding {}", portDescriptions);
594 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700595
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800596 // Possible situation:
597 // Device connected and became master for short period of time,
598 // but lost mastership before this instance had the chance to
599 // retrieve term information.
600
601 // Information dropped here is expected to be recoverable by
602 // device probing after mastership change
603
604 return Collections.emptyList();
605 }
606 log.debug("timestamp for {} {}", deviceId, newTimestamp);
607
608 final Timestamped<List<PortDescription>> timestampedInput
609 = new Timestamped<>(portDescriptions, newTimestamp);
610 final Timestamped<List<PortDescription>> merged;
611
612 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
613
614 synchronized (device) {
615 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
616 final DeviceDescriptions descs = device.get(providerId);
617 List<PortDescription> mergedList =
618 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700619 .transform(input ->
620 // lookup merged port description
621 descs.getPortDesc(input.portNumber()).value()
622 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700623 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800624 }
625
626 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700627 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700628 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800629 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
630 }
631
632 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800633 // Only forward for ConfigProvider
634 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800635 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta89461772016-01-26 12:18:10 -0800636 return Collections.emptyList();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800637 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800638 // FIXME Temporary hack for NPE (ONOS-1171).
639 // Proper fix is to implement forwarding to master on ConfigProvider
640 // redo ONOS-490
641 if (deviceNode == null) {
642 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800643 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800644 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800645
646 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800647
648 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700649 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800650 /* error log:
651 log.warn("Failed to process injected ports of device id: {} " +
652 "(cluster messaging failed: {})",
653 deviceId, e);
654 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700655 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700656
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800657 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700658 }
659
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700660 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700661 DeviceId deviceId,
662 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700663
664 Device device = devices.get(deviceId);
Ray Milkey9ef22232016-07-14 12:42:37 -0700665 if (device == null) {
666 log.debug("Device is no longer valid: {}", deviceId);
667 return Collections.emptyList();
668 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700669
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700670 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700671 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
672
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700673 List<DeviceEvent> events = new ArrayList<>();
674 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700675
676 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
677 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700678 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700679 }
680
681 DeviceDescriptions descs = descsMap.get(providerId);
682 // every provider must provide DeviceDescription.
683 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700684 "Device description for Device ID %s from Provider %s was not found",
685 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700686
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700687 Map<PortNumber, Port> ports = getPortMap(deviceId);
688
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700689 final Timestamp newTimestamp = portDescriptions.timestamp();
690
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700691 // Add new ports
692 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700693 for (PortDescription portDescription : portDescriptions.value()) {
694 final PortNumber number = portDescription.portNumber();
695 processed.add(number);
696
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700697 final Port oldPort = ports.get(number);
698 final Port newPort;
699
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700700
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700701 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
702 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700703 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700704 // on new port or valid update
705 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700706 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700707 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700708 newPort = composePort(device, number, descsMap);
709 } else {
710 // outdated event, ignored.
711 continue;
712 }
713
714 events.add(oldPort == null ?
715 createPort(device, newPort, ports) :
716 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700717 }
718
719 events.addAll(pruneOldPorts(device, ports, processed));
720 }
721 return FluentIterable.from(events).filter(notNull()).toList();
722 }
723
724 // Creates a new port based on the port description adds it to the map and
725 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700726 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700727 private DeviceEvent createPort(Device device, Port newPort,
728 Map<PortNumber, Port> ports) {
729 ports.put(newPort.number(), newPort);
730 return new DeviceEvent(PORT_ADDED, device, newPort);
731 }
732
733 // Checks if the specified port requires update and if so, it replaces the
734 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700735 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700736 private DeviceEvent updatePort(Device device, Port oldPort,
737 Port newPort,
738 Map<PortNumber, Port> ports) {
739 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700740 oldPort.type() != newPort.type() ||
741 oldPort.portSpeed() != newPort.portSpeed() ||
742 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700743 ports.put(oldPort.number(), newPort);
744 return new DeviceEvent(PORT_UPDATED, device, newPort);
745 }
746 return null;
747 }
748
749 // Prunes the specified list of ports based on which ports are in the
750 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700751 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700752 private List<DeviceEvent> pruneOldPorts(Device device,
753 Map<PortNumber, Port> ports,
754 Set<PortNumber> processed) {
755 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700756 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700757 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700758 Entry<PortNumber, Port> e = iterator.next();
759 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700760 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700761 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700762 iterator.remove();
763 }
764 }
765 return events;
766 }
767
768 // Gets the map of ports for the specified device; if one does not already
769 // exist, it creates and registers a new one.
770 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
Yuta HIGUCHIc2e68152016-08-16 13:47:36 -0700771 return devicePorts.computeIfAbsent(deviceId, k -> new ConcurrentHashMap<>());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700772 }
773
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700774 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700775 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700776 Map<ProviderId, DeviceDescriptions> r;
777 r = deviceDescs.get(deviceId);
778 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700779 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700780 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
781 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
782 if (concurrentlyAdded != null) {
783 r = concurrentlyAdded;
784 }
785 }
786 return r;
787 }
788
789 // Guarded by deviceDescs value (=Device lock)
790 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
791 Map<ProviderId, DeviceDescriptions> device,
792 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700793 synchronized (device) {
794 DeviceDescriptions r = device.get(providerId);
795 if (r == null) {
796 r = new DeviceDescriptions(deltaDesc);
797 device.put(providerId, r);
798 }
799 return r;
800 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700801 }
802
803 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700804 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
805 DeviceId deviceId,
806 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700807 final Timestamp newTimestamp;
808 try {
809 newTimestamp = deviceClockService.getTimestamp(deviceId);
810 } catch (IllegalStateException e) {
811 log.info("Timestamp was not available for device {}", deviceId);
812 log.debug(" discarding {}", portDescription);
813 // Failed to generate timestamp. Ignoring.
814 // See updatePorts comment
815 return null;
816 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700817 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700818 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700819 final DeviceEvent event;
820 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800821 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
822 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700823 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800824 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700825 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700826 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700827 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700828 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700829 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800830 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700831 }
832 return event;
833 }
834
835 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700836 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700837 Device device = devices.get(deviceId);
838 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
839
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700840 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700841 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
842
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700843 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700844
845 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
846 log.debug("Ignoring outdated event: {}", deltaDesc);
847 return null;
848 }
849
850 DeviceDescriptions descs = descsMap.get(providerId);
851 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700852 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700853 "Device description for Device ID %s from Provider %s was not found",
854 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700855
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700856 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
857 final PortNumber number = deltaDesc.value().portNumber();
858 final Port oldPort = ports.get(number);
859 final Port newPort;
860
861 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
862 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700863 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700864 // on new port or valid update
865 // update description
866 descs.putPortDesc(deltaDesc);
867 newPort = composePort(device, number, descsMap);
868 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700869 // same or outdated event, ignored.
870 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700871 return null;
872 }
873
874 if (oldPort == null) {
875 return createPort(device, newPort, ports);
876 } else {
877 return updatePort(device, oldPort, newPort, ports);
878 }
879 }
880 }
881
882 @Override
883 public List<Port> getPorts(DeviceId deviceId) {
884 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
885 if (ports == null) {
886 return Collections.emptyList();
887 }
888 return ImmutableList.copyOf(ports.values());
889 }
890
891 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700892 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
893 DeviceId deviceId) {
894 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
895 if (descs == null) {
896 return null;
897 }
898 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
899 final Optional<DeviceDescriptions> devDescs;
900 synchronized (descs) {
901 devDescs = Optional.ofNullable(descs.get(pid));
902 }
903 // DeviceDescriptions is concurrent access-safe
904 return devDescs
905 .map(dd -> dd.getPortDescs().values().stream()
906 .map(Timestamped::value))
907 .orElse(Stream.empty());
908 }
909
910 @Override
sangho538108b2015-04-08 14:29:20 -0700911 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200912 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700913
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200914 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
915 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
916 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
917
918 if (prvStatsMap != null) {
919 for (PortStatistics newStats : newStatsCollection) {
920 PortNumber port = PortNumber.portNumber(newStats.port());
921 PortStatistics prvStats = prvStatsMap.get(port);
922 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
923 PortStatistics deltaStats = builder.build();
924 if (prvStats != null) {
925 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
926 }
927 deltaStatsMap.put(port, deltaStats);
928 newStatsMap.put(port, newStats);
929 }
930 } else {
931 for (PortStatistics newStats : newStatsCollection) {
932 PortNumber port = PortNumber.portNumber(newStats.port());
933 newStatsMap.put(port, newStats);
934 }
sangho538108b2015-04-08 14:29:20 -0700935 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200936 devicePortDeltaStats.put(deviceId, deltaStatsMap);
937 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200938 // DeviceEvent returns null because of InternalPortStatsListener usage
939 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200940 }
941
942 /**
943 * Calculate delta statistics by subtracting previous from new statistics.
944 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700945 * @param deviceId device identifier
946 * @param prvStats previous port statistics
947 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200948 * @return PortStatistics
949 */
950 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
951 // calculate time difference
952 long deltaStatsSec, deltaStatsNano;
953 if (newStats.durationNano() < prvStats.durationNano()) {
954 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
955 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
956 } else {
957 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
958 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
959 }
960 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
961 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
962 .setPort(newStats.port())
963 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
964 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
965 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
966 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
967 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
968 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
969 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
970 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
971 .setDurationSec(deltaStatsSec)
972 .setDurationNano(deltaStatsNano)
973 .build();
974 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700975 }
976
977 @Override
978 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700979 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
980 if (portStats == null) {
981 return Collections.emptyList();
982 }
983 return ImmutableList.copyOf(portStats.values());
984 }
985
986 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530987 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
988 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
989 if (portStatsMap == null) {
990 return null;
991 }
992 PortStatistics portStats = portStatsMap.get(portNumber);
993 return portStats;
994 }
995
996 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200997 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
998 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
999 if (portStats == null) {
1000 return Collections.emptyList();
1001 }
1002 return ImmutableList.copyOf(portStats.values());
1003 }
1004
1005 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +05301006 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
1007 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
1008 if (portStatsMap == null) {
1009 return null;
1010 }
1011 PortStatistics portStats = portStatsMap.get(portNumber);
1012 return portStats;
1013 }
1014
1015 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001016 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
1017 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1018 return ports == null ? null : ports.get(portNumber);
1019 }
1020
1021 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -07001022 public PortDescription getPortDescription(ProviderId pid,
1023 DeviceId deviceId,
1024 PortNumber portNumber) {
1025 Map<ProviderId, DeviceDescriptions> descs = this.deviceDescs.get(deviceId);
1026 if (descs == null) {
1027 return null;
1028 }
1029 // inner-Map(=descs) is HashMap, thus requires synchronization even for reads
1030 final Optional<DeviceDescriptions> devDescs;
1031 synchronized (descs) {
1032 devDescs = Optional.ofNullable(descs.get(pid));
1033 }
1034 // DeviceDescriptions is concurrent access-safe
1035 return devDescs
1036 .map(deviceDescriptions -> deviceDescriptions.getPortDesc(portNumber))
1037 .map(Timestamped::value)
1038 .orElse(null);
1039 }
1040
1041 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001042 public boolean isAvailable(DeviceId deviceId) {
1043 return availableDevices.contains(deviceId);
1044 }
1045
1046 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001047 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001048 final NodeId myId = clusterService.getLocalNode().id();
1049 NodeId master = mastershipService.getMasterFor(deviceId);
1050
1051 // if there exist a master, forward
1052 // if there is no master, try to become one and process
1053
1054 boolean relinquishAtEnd = false;
1055 if (master == null) {
1056 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1057 if (myRole != MastershipRole.NONE) {
1058 relinquishAtEnd = true;
1059 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001060 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001061 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001062 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -07001063 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001064 master = myId;
1065 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -07001066 }
1067
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001068 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001069 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001070 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001071
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001072 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001073 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001074 /* error log:
1075 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
1076 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001077
Brian O'Connor5eb77c82015-03-02 18:09:39 -08001078 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001079 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001080 }
1081
1082 // I have control..
1083
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -07001084 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001085 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001086 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001087 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001088 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -08001089 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001090 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001091 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001092 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001093 mastershipService.relinquishMastership(deviceId);
1094 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001095 return event;
1096 }
1097
1098 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
1099 Timestamp timestamp) {
1100
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001101 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001102 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001103 // accept removal request if given timestamp is newer than
1104 // the latest Timestamp from Primary provider
1105 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -08001106 if (primDescs == null) {
1107 return null;
1108 }
1109
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001110 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
1111 if (timestamp.compareTo(lastTimestamp) <= 0) {
1112 // outdated event ignore
1113 return null;
1114 }
1115 removalRequest.put(deviceId, timestamp);
1116
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001117 Device device = devices.remove(deviceId);
1118 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001119 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1120 if (ports != null) {
1121 ports.clear();
1122 }
1123 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001124 descs.clear();
1125 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001126 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001127 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001128 }
1129
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001130 /**
1131 * Checks if given timestamp is superseded by removal request
1132 * with more recent timestamp.
1133 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001134 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001135 * @param timestampToCheck timestamp of an event to check
1136 * @return true if device is already removed
1137 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001138 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1139 Timestamp removalTimestamp = removalRequest.get(deviceId);
1140 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001141 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001142 // removalRequest is more recent
1143 return true;
1144 }
1145 return false;
1146 }
1147
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001148 /**
1149 * Returns a Device, merging description given from multiple Providers.
1150 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001151 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001152 * @param providerDescs Collection of Descriptions from multiple providers
1153 * @return Device instance
1154 */
1155 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001156 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001157
Thomas Vachuska444eda62014-10-28 13:09:42 -07001158 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001159
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001160 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001161
1162 DeviceDescriptions desc = providerDescs.get(primary);
1163
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001164 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001165 Type type = base.type();
1166 String manufacturer = base.manufacturer();
1167 String hwVersion = base.hwVersion();
1168 String swVersion = base.swVersion();
1169 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001170 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001171 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1172 annotations = merge(annotations, base.annotations());
1173
1174 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1175 if (e.getKey().equals(primary)) {
1176 continue;
1177 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001178 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001179 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001180 // Currently assuming there will never be a key conflict between
1181 // providers
1182
1183 // annotation merging. not so efficient, should revisit later
1184 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1185 }
1186
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001187 return new DefaultDevice(primary, deviceId, type, manufacturer,
1188 hwVersion, swVersion, serialNumber,
1189 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001190 }
1191
Marc De Leenheer88194c32015-05-29 22:10:59 -07001192 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1193 PortDescription description, Annotations annotations) {
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001194 // FIXME this switch need to go away once all ports are done.
Marc De Leenheer88194c32015-05-29 22:10:59 -07001195 switch (description.type()) {
1196 case OMS:
HIGUCHI Yuta95d83e82016-04-26 12:13:48 -07001197 if (description instanceof OmsPortDescription) {
1198 // remove if-block once deprecation is complete
1199 OmsPortDescription omsDesc = (OmsPortDescription) description;
1200 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1201 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1202 }
1203 // same as default
1204 return new DefaultPort(device, number, isEnabled, description.type(),
1205 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001206 case OCH:
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001207 if (description instanceof OchPortDescription) {
1208 // remove if-block once Och deprecation is complete
1209 OchPortDescription ochDesc = (OchPortDescription) description;
1210 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1211 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1212 }
1213 return new DefaultPort(device, number, isEnabled, description.type(),
1214 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001215 case ODUCLT:
HIGUCHI Yuta4c0ef6b2016-05-02 19:45:41 -07001216 if (description instanceof OduCltPortDescription) {
1217 // remove if-block once deprecation is complete
1218 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1219 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1220 }
1221 // same as default
1222 return new DefaultPort(device, number, isEnabled, description.type(),
1223 description.portSpeed(), annotations);
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +02001224 case OTU:
HIGUCHI Yuta5be3e822016-05-03 13:51:42 -07001225 if (description instanceof OtuPortDescription) {
1226 // remove if-block once deprecation is complete
1227 OtuPortDescription otuDesc = (OtuPortDescription) description;
1228 return new OtuPort(device, number, isEnabled, otuDesc.signalType(), annotations);
1229 }
1230 // same as default
1231 return new DefaultPort(device, number, isEnabled, description.type(),
1232 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001233 default:
1234 return new DefaultPort(device, number, isEnabled, description.type(),
1235 description.portSpeed(), annotations);
1236 }
1237 }
1238
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001239 /**
1240 * Returns a Port, merging description given from multiple Providers.
1241 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001242 * @param device device the port is on
1243 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001244 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001245 * @return Port instance
1246 */
1247 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001248 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001249
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001250 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001251 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001252 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001253 boolean isEnabled = false;
1254 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001255 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001256 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1257 if (portDesc != null) {
1258 isEnabled = portDesc.value().isEnabled();
1259 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001260 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001261 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001262 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001263 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001264 if (e.getKey().equals(primary)) {
1265 continue;
1266 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001267 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001268 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001269 // Currently assuming there will never be a key conflict between
1270 // providers
1271
1272 // annotation merging. not so efficient, should revisit later
1273 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1274 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001275 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1276 continue;
1277 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001278 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001279 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001280 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001281 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001282 }
1283 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001284 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001285 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001286 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001287 PortDescription current = portDesc.value();
1288 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001289 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001290 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001291 }
1292
1293 /**
1294 * @return primary ProviderID, or randomly chosen one if none exists
1295 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001296 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001297 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001298 ProviderId fallBackPrimary = null;
1299 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1300 if (!e.getKey().isAncillary()) {
1301 return e.getKey();
1302 } else if (fallBackPrimary == null) {
1303 // pick randomly as a fallback in case there is no primary
1304 fallBackPrimary = e.getKey();
1305 }
1306 }
1307 return fallBackPrimary;
1308 }
1309
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001310 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001311 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001312 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001313 return providerDescs.get(pid);
1314 }
1315
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001316 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001317 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001318 }
1319
Jonathan Hart7d656f42015-01-27 14:07:23 -08001320 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001321 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001322 }
Madan Jampani47c93732014-10-06 20:46:08 -07001323
Jonathan Hart7d656f42015-01-27 14:07:23 -08001324 private void notifyPeers(InternalDeviceEvent event) {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001325 broadcastMessage(DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001326 }
1327
Jonathan Hart7d656f42015-01-27 14:07:23 -08001328 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001329 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001330 }
1331
Jonathan Hart7d656f42015-01-27 14:07:23 -08001332 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001333 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001334 }
1335
Jonathan Hart7d656f42015-01-27 14:07:23 -08001336 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001337 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001338 }
1339
Jonathan Hart7d656f42015-01-27 14:07:23 -08001340 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001341 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1342 }
1343
1344 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1345 try {
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001346 unicastMessage(recipient, DEVICE_UPDATE, event);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001347 } catch (IOException e) {
1348 log.error("Failed to send" + event + " to " + recipient, e);
1349 }
1350 }
1351
1352 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1353 try {
1354 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1355 } catch (IOException e) {
1356 log.error("Failed to send" + event + " to " + recipient, e);
1357 }
1358 }
1359
1360 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1361 try {
1362 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1363 } catch (IOException e) {
1364 log.error("Failed to send" + event + " to " + recipient, e);
1365 }
1366 }
1367
1368 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1369 try {
1370 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1371 } catch (IOException e) {
1372 log.error("Failed to send" + event + " to " + recipient, e);
1373 }
1374 }
1375
1376 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1377 try {
1378 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1379 } catch (IOException e) {
1380 log.error("Failed to send" + event + " to " + recipient, e);
1381 }
1382 }
1383
1384 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1385 final NodeId self = clusterService.getLocalNode().id();
1386
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001387 final int numDevices = deviceDescs.size();
1388 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1389 final int portsPerDevice = 8; // random factor to minimize reallocation
1390 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1391 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001392
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001393 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001394
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001395 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001396 synchronized (devDescs) {
1397
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001398 // send device offline timestamp
1399 Timestamp lOffline = this.offline.get(deviceId);
1400 if (lOffline != null) {
1401 adOffline.put(deviceId, lOffline);
1402 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001403
1404 for (Entry<ProviderId, DeviceDescriptions>
1405 prov : devDescs.entrySet()) {
1406
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001407 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001408 final ProviderId provId = prov.getKey();
1409 final DeviceDescriptions descs = prov.getValue();
1410
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001411 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001412 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001413
1414 for (Entry<PortNumber, Timestamped<PortDescription>>
1415 portDesc : descs.getPortDescs().entrySet()) {
1416
1417 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001418 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001419 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001420 }
1421 }
1422 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001423 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001424
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001425 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001426 }
1427
1428 /**
1429 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001430 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001431 * Notify sender about out-dated information using regular replication message.
1432 * Send back advertisement to sender if not in sync.
1433 *
1434 * @param advertisement to respond to
1435 */
1436 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1437
1438 final NodeId sender = advertisement.sender();
1439
1440 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1441 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1442 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1443
1444 // Fragments to request
1445 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1446 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1447
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001448 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001449 final DeviceId deviceId = de.getKey();
1450 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1451
1452 synchronized (lDevice) {
1453 // latestTimestamp across provider
1454 // Note: can be null initially
1455 Timestamp localLatest = offline.get(deviceId);
1456
1457 // handle device Ads
1458 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1459 final ProviderId provId = prov.getKey();
1460 final DeviceDescriptions lDeviceDescs = prov.getValue();
1461
1462 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1463
1464
1465 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1466 Timestamp advDevTimestamp = devAds.get(devFragId);
1467
Jonathan Hart403ea932015-02-20 16:23:00 -08001468 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1469 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001470 // remote does not have it or outdated, suggest
1471 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1472 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1473 // local is outdated, request
1474 reqDevices.add(devFragId);
1475 }
1476
1477 // handle port Ads
1478 for (Entry<PortNumber, Timestamped<PortDescription>>
1479 pe : lDeviceDescs.getPortDescs().entrySet()) {
1480
1481 final PortNumber num = pe.getKey();
1482 final Timestamped<PortDescription> lPort = pe.getValue();
1483
1484 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1485
1486 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001487 if (advPortTimestamp == null || lPort.isNewerThan(
1488 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001489 // remote does not have it or outdated, suggest
1490 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1491 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1492 // local is outdated, request
1493 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1494 reqPorts.add(portFragId);
1495 }
1496
1497 // remove port Ad already processed
1498 portAds.remove(portFragId);
1499 } // end local port loop
1500
1501 // remove device Ad already processed
1502 devAds.remove(devFragId);
1503
1504 // find latest and update
1505 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1506 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001507 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001508 localLatest = providerLatest;
1509 }
1510 } // end local provider loop
1511
1512 // checking if remote timestamp is more recent.
1513 Timestamp rOffline = offlineAds.get(deviceId);
1514 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001515 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001516 // remote offline timestamp suggests that the
1517 // device is off-line
1518 markOfflineInternal(deviceId, rOffline);
1519 }
1520
1521 Timestamp lOffline = offline.get(deviceId);
1522 if (lOffline != null && rOffline == null) {
1523 // locally offline, but remote is online, suggest offline
1524 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1525 }
1526
1527 // remove device offline Ad already processed
1528 offlineAds.remove(deviceId);
1529 } // end local device loop
1530 } // device lock
1531
1532 // If there is any Ads left, request them
1533 log.trace("Ads left {}, {}", devAds, portAds);
1534 reqDevices.addAll(devAds.keySet());
1535 reqPorts.addAll(portAds.keySet());
1536
1537 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1538 log.trace("Nothing to request to remote peer {}", sender);
1539 return;
1540 }
1541
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001542 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001543
1544 // 2-way Anti-Entropy for now
1545 try {
1546 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1547 } catch (IOException e) {
1548 log.error("Failed to send response advertisement to " + sender, e);
1549 }
1550
1551// Sketch of 3-way Anti-Entropy
1552// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1553// ClusterMessage message = new ClusterMessage(
1554// clusterService.getLocalNode().id(),
1555// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1556// SERIALIZER.encode(request));
1557//
1558// try {
1559// clusterCommunicator.unicast(message, advertisement.sender());
1560// } catch (IOException e) {
1561// log.error("Failed to send advertisement reply to "
1562// + advertisement.sender(), e);
1563// }
Madan Jampani47c93732014-10-06 20:46:08 -07001564 }
1565
Madan Jampani255a58b2014-10-09 12:08:20 -07001566 private void notifyDelegateIfNotNull(DeviceEvent event) {
1567 if (event != null) {
1568 notifyDelegate(event);
1569 }
1570 }
1571
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001572 private final class SendAdvertisementTask implements Runnable {
1573
1574 @Override
1575 public void run() {
1576 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001577 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001578 return;
1579 }
1580
1581 try {
1582 final NodeId self = clusterService.getLocalNode().id();
1583 Set<ControllerNode> nodes = clusterService.getNodes();
1584
1585 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1586 .transform(toNodeId())
1587 .toList();
1588
1589 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001590 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001591 return;
1592 }
1593
1594 NodeId peer;
1595 do {
1596 int idx = RandomUtils.nextInt(0, nodeIds.size());
1597 peer = nodeIds.get(idx);
1598 } while (peer.equals(self));
1599
1600 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1601
1602 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001603 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001604 return;
1605 }
1606
1607 try {
1608 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1609 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001610 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001611 return;
1612 }
1613 } catch (Exception e) {
1614 // catch all Exception to avoid Scheduled task being suppressed.
1615 log.error("Exception thrown while sending advertisement", e);
1616 }
1617 }
1618 }
1619
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001620 private void handleDeviceEvent(InternalDeviceEvent event) {
1621 ProviderId providerId = event.providerId();
1622 DeviceId deviceId = event.deviceId();
1623 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001624
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001625 try {
1626 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId,
1627 deviceDescription));
1628 } catch (Exception e) {
1629 log.warn("Exception thrown handling device update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001630 }
1631 }
1632
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001633 private void handleDeviceOfflineEvent(InternalDeviceOfflineEvent event) {
1634 DeviceId deviceId = event.deviceId();
1635 Timestamp timestamp = event.timestamp();
Madan Jampani25322532014-10-08 11:20:38 -07001636
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001637 try {
1638 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1639 } catch (Exception e) {
1640 log.warn("Exception thrown handling device offline", e);
Madan Jampani25322532014-10-08 11:20:38 -07001641 }
1642 }
1643
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001644 private void handleRemoveRequest(DeviceId did) {
1645 try {
1646 removeDevice(did);
1647 } catch (Exception e) {
1648 log.warn("Exception thrown handling device remove", e);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001649 }
1650 }
1651
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001652 private void handleDeviceRemovedEvent(InternalDeviceRemovedEvent event) {
1653 DeviceId deviceId = event.deviceId();
1654 Timestamp timestamp = event.timestamp();
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001655
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001656 try {
1657 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1658 } catch (Exception e) {
1659 log.warn("Exception thrown handling device removed", e);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001660 }
1661 }
1662
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001663 private void handlePortEvent(InternalPortEvent event) {
1664 ProviderId providerId = event.providerId();
1665 DeviceId deviceId = event.deviceId();
1666 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
Madan Jampani47c93732014-10-06 20:46:08 -07001667
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001668 if (getDevice(deviceId) == null) {
1669 log.debug("{} not found on this node yet, ignoring.", deviceId);
1670 // Note: dropped information will be recovered by anti-entropy
1671 return;
1672 }
Madan Jampani47c93732014-10-06 20:46:08 -07001673
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001674 try {
1675 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1676 } catch (Exception e) {
1677 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001678 }
1679 }
1680
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001681 private void handlePortStatusEvent(InternalPortStatusEvent event) {
1682 ProviderId providerId = event.providerId();
1683 DeviceId deviceId = event.deviceId();
1684 Timestamped<PortDescription> portDescription = event.portDescription();
Madan Jampani47c93732014-10-06 20:46:08 -07001685
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001686 if (getDevice(deviceId) == null) {
1687 log.debug("{} not found on this node yet, ignoring.", deviceId);
1688 // Note: dropped information will be recovered by anti-entropy
1689 return;
1690 }
Madan Jampani47c93732014-10-06 20:46:08 -07001691
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001692 try {
1693 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1694 } catch (Exception e) {
1695 log.warn("Exception thrown handling port update", e);
Madan Jampani47c93732014-10-06 20:46:08 -07001696 }
1697 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001698
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001699 private void handleDeviceAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1700 try {
1701 handleAdvertisement(advertisement);
1702 } catch (Exception e) {
1703 log.warn("Exception thrown handling Device advertisements.", e);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001704 }
1705 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001706
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001707 private void handleDeviceInjectedEvent(DeviceInjectedEvent event) {
1708 ProviderId providerId = event.providerId();
1709 DeviceId deviceId = event.deviceId();
1710 DeviceDescription deviceDescription = event.deviceDescription();
1711 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1712 // workaround for ONOS-1208
1713 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1714 return;
1715 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001716
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001717 try {
1718 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1719 } catch (Exception e) {
1720 log.warn("Exception thrown handling device injected event.", e);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001721 }
1722 }
1723
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001724 private void handlePortInjectedEvent(PortInjectedEvent event) {
1725 ProviderId providerId = event.providerId();
1726 DeviceId deviceId = event.deviceId();
1727 List<PortDescription> portDescriptions = event.portDescriptions();
1728 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1729 // workaround for ONOS-1208
1730 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1731 return;
1732 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001733
Jonathan Hart46ab5cc2016-09-15 15:42:39 -07001734 try {
1735 updatePorts(providerId, deviceId, portDescriptions);
1736 } catch (Exception e) {
1737 log.warn("Exception thrown handling port injected event.", e);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001738 }
1739 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001740
1741 private class InternalPortStatsListener
1742 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1743 @Override
1744 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1745 if (event.type() == PUT) {
1746 Device device = devices.get(event.key());
1747 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -07001748 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001749 }
1750 }
1751 }
1752 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001753}