blob: d2d450ed69ab8fb0faf810c09ac27bf502f30897 [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
18import com.google.common.collect.FluentIterable;
19import com.google.common.collect.ImmutableList;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -070020import com.google.common.collect.Maps;
21import com.google.common.collect.Sets;
Dusan Pajin11ff4a82015-08-20 18:03:05 +020022
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070023import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070024import org.apache.felix.scr.annotations.Activate;
25import org.apache.felix.scr.annotations.Component;
26import org.apache.felix.scr.annotations.Deactivate;
27import org.apache.felix.scr.annotations.Reference;
28import org.apache.felix.scr.annotations.ReferenceCardinality;
29import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080030import org.onlab.packet.ChassisId;
31import org.onlab.util.KryoNamespace;
32import org.onlab.util.NewConcurrentHashMap;
Brian O'Connorabafb502014-12-02 22:26:20 -080033import org.onosproject.cluster.ClusterService;
34import org.onosproject.cluster.ControllerNode;
35import org.onosproject.cluster.NodeId;
36import org.onosproject.mastership.MastershipService;
37import org.onosproject.mastership.MastershipTerm;
38import org.onosproject.mastership.MastershipTermService;
Marc De Leenheer88194c32015-05-29 22:10:59 -070039import org.onosproject.net.Annotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.net.AnnotationsUtil;
41import org.onosproject.net.DefaultAnnotations;
42import org.onosproject.net.DefaultDevice;
43import org.onosproject.net.DefaultPort;
44import org.onosproject.net.Device;
45import org.onosproject.net.Device.Type;
46import org.onosproject.net.DeviceId;
47import org.onosproject.net.MastershipRole;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070048import org.onosproject.net.OchPort;
49import org.onosproject.net.OduCltPort;
50import org.onosproject.net.OmsPort;
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +020051import org.onosproject.net.OtuPort;
Brian O'Connorabafb502014-12-02 22:26:20 -080052import org.onosproject.net.Port;
53import org.onosproject.net.PortNumber;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070054import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.net.device.DeviceClockService;
56import org.onosproject.net.device.DeviceDescription;
57import org.onosproject.net.device.DeviceEvent;
58import org.onosproject.net.device.DeviceStore;
59import org.onosproject.net.device.DeviceStoreDelegate;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070060import org.onosproject.net.device.OchPortDescription;
61import org.onosproject.net.device.OduCltPortDescription;
62import org.onosproject.net.device.OmsPortDescription;
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +020063import org.onosproject.net.device.OtuPortDescription;
Brian O'Connorabafb502014-12-02 22:26:20 -080064import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070065import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080066import org.onosproject.net.provider.ProviderId;
67import org.onosproject.store.AbstractStore;
68import org.onosproject.store.Timestamp;
69import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
70import org.onosproject.store.cluster.messaging.ClusterMessage;
71import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
72import org.onosproject.store.cluster.messaging.MessageSubject;
73import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070074import org.onosproject.store.serializers.KryoNamespaces;
HIGUCHI Yutae7290652016-05-18 11:29:01 -070075import org.onosproject.store.serializers.StoreSerializer;
Brian O'Connor6de2e202015-05-21 14:30:41 -070076import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070077import org.onosproject.store.service.EventuallyConsistentMap;
78import org.onosproject.store.service.EventuallyConsistentMapEvent;
79import org.onosproject.store.service.EventuallyConsistentMapListener;
80import org.onosproject.store.service.MultiValuedTimestamp;
81import org.onosproject.store.service.StorageService;
82import org.onosproject.store.service.WallClockTimestamp;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070083import org.slf4j.Logger;
84
Madan Jampani47c93732014-10-06 20:46:08 -070085import java.io.IOException;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070086import java.util.ArrayList;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070087import java.util.Collection;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070088import java.util.Collections;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070089import java.util.HashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070090import java.util.HashSet;
91import java.util.Iterator;
92import java.util.List;
93import java.util.Map;
94import java.util.Map.Entry;
95import java.util.Objects;
96import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070097import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080098import java.util.concurrent.ExecutorService;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070099import java.util.concurrent.ScheduledExecutorService;
100import java.util.concurrent.TimeUnit;
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;
107import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800108import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800109import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800110import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
111import static org.onosproject.net.DefaultAnnotations.merge;
112import static org.onosproject.net.device.DeviceEvent.Type.*;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800113import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700114import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800115import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700116
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700117/**
118 * Manages inventory of infrastructure devices using gossip protocol to distribute
119 * information.
120 */
121@Component(immediate = true)
122@Service
123public class GossipDeviceStore
124 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
125 implements DeviceStore {
126
127 private final Logger log = getLogger(getClass());
128
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700129 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800130 // Timeout in milliseconds to process device or ports on remote master node
131 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700132
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700133 // innerMap is used to lock a Device, thus instance should never be replaced.
134 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700135 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700136 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700137
138 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700139 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
140 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700141
142 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200143 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700144 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
145 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700146
147 // to be updated under Device lock
148 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
149 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700150
151 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700152 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700153
154 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700155 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700156
Madan Jampani47c93732014-10-06 20:46:08 -0700157 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700158 protected StorageService storageService;
159
160 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700161 protected ClusterCommunicationService clusterCommunicator;
162
Madan Jampani53e44e62014-10-07 12:39:51 -0700163 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
164 protected ClusterService clusterService;
165
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700166 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
167 protected MastershipService mastershipService;
168
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800169 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
170 protected MastershipTermService termService;
171
172
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700173 protected static final StoreSerializer SERIALIZER = StoreSerializer.using(KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800174 .register(DistributedStoreSerializers.STORE_COMMON)
175 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
176 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
177 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700178 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800179 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
180 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700181 .register(DeviceAntiEntropyAdvertisement.class)
182 .register(DeviceFragmentId.class)
183 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800184 .register(DeviceInjectedEvent.class)
185 .register(PortInjectedEvent.class)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700186 .build("GossipDevice"));
Madan Jampani53e44e62014-10-07 12:39:51 -0700187
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800188 private ExecutorService executor;
189
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800190 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700191
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800192 // TODO make these anti-entropy parameters configurable
193 private long initialDelaySec = 5;
194 private long periodSec = 5;
195
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700196 @Activate
197 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800198 executor = newCachedThreadPool(groupedThreads("onos/device", "fg-%d", log));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800199
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800200 backgroundExecutor =
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800201 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d", log)));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700202
Madan Jampani2af244a2015-02-22 13:12:01 -0800203 clusterCommunicator.addSubscriber(
204 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
205 clusterCommunicator.addSubscriber(
206 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
207 new InternalDeviceOfflineEventListener(),
208 executor);
209 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700210 new InternalRemoveRequestListener(),
211 executor);
Madan Jampani2af244a2015-02-22 13:12:01 -0800212 clusterCommunicator.addSubscriber(
213 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
214 clusterCommunicator.addSubscriber(
215 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
216 clusterCommunicator.addSubscriber(
217 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
218 clusterCommunicator.addSubscriber(
219 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
220 new InternalDeviceAdvertisementListener(),
221 backgroundExecutor);
222 clusterCommunicator.addSubscriber(
223 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
224 clusterCommunicator.addSubscriber(
225 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
226
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700227 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800228 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700229 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700230
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700231 // Create a distributed map for port stats.
232 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
233 .register(KryoNamespaces.API)
HIGUCHI Yuta03666a32016-05-18 11:49:09 -0700234 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
235 .register(MultiValuedTimestamp.class);
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700236
237 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
238 .withName("port-stats")
239 .withSerializer(deviceDataSerializer)
240 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
Madan Jampanibcf1a482015-06-24 19:05:56 -0700241 .withTimestampProvider((k, v) -> new WallClockTimestamp())
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700242 .withTombstonesDisabled()
243 .build();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200244 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
245 eventuallyConsistentMapBuilder()
246 .withName("port-stats-delta")
247 .withSerializer(deviceDataSerializer)
248 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
249 .withTimestampProvider((k, v) -> new WallClockTimestamp())
250 .withTombstonesDisabled()
251 .build();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700252 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700253 log.info("Started");
254 }
255
256 @Deactivate
257 public void deactivate() {
Madan Jampani632f16b2015-08-11 12:42:59 -0700258 devicePortStats.destroy();
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200259 devicePortDeltaStats.destroy();
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800260 executor.shutdownNow();
261
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800262 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700263 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800264 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700265 log.error("Timeout during executor shutdown");
266 }
267 } catch (InterruptedException e) {
268 log.error("Error during executor shutdown", e);
269 }
270
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700271 deviceDescs.clear();
272 devices.clear();
273 devicePorts.clear();
274 availableDevices.clear();
275 log.info("Stopped");
276 }
277
278 @Override
279 public int getDeviceCount() {
280 return devices.size();
281 }
282
283 @Override
284 public Iterable<Device> getDevices() {
285 return Collections.unmodifiableCollection(devices.values());
286 }
287
288 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800289 public Iterable<Device> getAvailableDevices() {
290 return FluentIterable.from(getDevices())
Sho SHIMIZU06a6c9f2015-06-12 14:49:06 -0700291 .filter(input -> isAvailable(input.id()));
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800292 }
293
294 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700295 public Device getDevice(DeviceId deviceId) {
296 return devices.get(deviceId);
297 }
298
299 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700300 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700301 DeviceId deviceId,
302 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800303 NodeId localNode = clusterService.getLocalNode().id();
304 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
305
306 // Process device update only if we're the master,
307 // otherwise signal the actual master.
308 DeviceEvent deviceEvent = null;
309 if (localNode.equals(deviceNode)) {
310
311 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
312 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
313 final Timestamped<DeviceDescription> mergedDesc;
314 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
315
316 synchronized (device) {
317 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
318 mergedDesc = device.get(providerId).getDeviceDesc();
319 }
320
321 if (deviceEvent != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700322 log.debug("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700323 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800324 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
325 }
326
327 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800328 // Only forward for ConfigProvider
329 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800330 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800331 return null;
332 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800333 // FIXME Temporary hack for NPE (ONOS-1171).
334 // Proper fix is to implement forwarding to master on ConfigProvider
335 // redo ONOS-490
336 if (deviceNode == null) {
337 // silently ignore
338 return null;
339 }
340
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800341
342 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
343 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800344
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800345 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700346 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800347 /* error log:
348 log.warn("Failed to process injected device id: {} desc: {} " +
349 "(cluster messaging failed: {})",
350 deviceId, deviceDescription, e);
351 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700352 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800353
354 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700355 }
356
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700357 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700358 DeviceId deviceId,
359 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700360
361 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800362 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700363 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700364
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800365 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700366 // locking per device
367
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700368 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
369 log.debug("Ignoring outdated event: {}", deltaDesc);
370 return null;
371 }
372
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800373 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700374
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700375 final Device oldDevice = devices.get(deviceId);
376 final Device newDevice;
377
378 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700379 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700380 // on new device or valid update
381 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800382 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700383 } else {
384 // outdated event, ignored.
385 return null;
386 }
387 if (oldDevice == null) {
388 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700389 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700390 } else {
391 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700392 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700393 }
394 }
395 }
396
397 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700398 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700399 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700400 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700401
402 // update composed device cache
403 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
404 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700405 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
406 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700407
408 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700409 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700410 }
411
412 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
413 }
414
415 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700416 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700417 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700418 Device oldDevice,
419 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700420 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700421 boolean propertiesChanged =
422 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700423 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
424 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700425 boolean annotationsChanged =
426 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700427
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700428 // Primary providers can respond to all changes, but ancillary ones
429 // should respond only to annotation changes.
alshabibdc5d8bd2015-11-02 15:41:29 -0800430 DeviceEvent event = null;
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700431 if ((providerId.isAncillary() && annotationsChanged) ||
432 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700433 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
434 if (!replaced) {
435 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700436 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
Jian Li68c4fc42016-01-11 16:07:03 -0800437 providerId, oldDevice, devices.get(newDevice.id()), newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700438 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700439
alshabibdc5d8bd2015-11-02 15:41:29 -0800440 event = new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700441 }
alshabibdc5d8bd2015-11-02 15:41:29 -0800442
443 if (!providerId.isAncillary()) {
444 boolean wasOnline = availableDevices.contains(newDevice.id());
445 markOnline(newDevice.id(), newTimestamp);
446 if (!wasOnline) {
447 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
448 }
449 }
450 return event;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700451 }
452
453 @Override
454 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700455 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700456 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700457 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700458 log.debug("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700459 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800460 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700461 }
462 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700463 }
464
465 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
466
467 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700468 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700469
470 // locking device
471 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700472
473 // accept off-line if given timestamp is newer than
474 // the latest Timestamp from Primary provider
475 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
476 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
477 if (timestamp.compareTo(lastTimestamp) <= 0) {
478 // outdated event ignore
479 return null;
480 }
481
482 offline.put(deviceId, timestamp);
483
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700484 Device device = devices.get(deviceId);
485 if (device == null) {
486 return null;
487 }
488 boolean removed = availableDevices.remove(deviceId);
489 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700490 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700491 }
492 return null;
493 }
494 }
495
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700496 /**
497 * Marks the device as available if the given timestamp is not outdated,
498 * compared to the time the device has been marked offline.
499 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700500 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700501 * @param timestamp of the event triggering this change.
502 * @return true if availability change request was accepted and changed the state
503 */
504 // Guarded by deviceDescs value (=Device lock)
505 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
506 // accept on-line if given timestamp is newer than
507 // the latest offline request Timestamp
508 Timestamp offlineTimestamp = offline.get(deviceId);
509 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700510 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700511
512 offline.remove(deviceId);
513 return availableDevices.add(deviceId);
514 }
515 return false;
516 }
517
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700518 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700519 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700520 DeviceId deviceId,
521 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700522
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800523 NodeId localNode = clusterService.getLocalNode().id();
524 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
525 // since it will trigger distributed store read.
526 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
527 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
528 // If we don't care much about topology performance, then it might be OK.
529 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700530
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800531 // Process port update only if we're the master of the device,
532 // otherwise signal the actual master.
533 List<DeviceEvent> deviceEvents = null;
534 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700535
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800536 final Timestamp newTimestamp;
537 try {
538 newTimestamp = deviceClockService.getTimestamp(deviceId);
539 } catch (IllegalStateException e) {
540 log.info("Timestamp was not available for device {}", deviceId);
541 log.debug(" discarding {}", portDescriptions);
542 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700543
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800544 // Possible situation:
545 // Device connected and became master for short period of time,
546 // but lost mastership before this instance had the chance to
547 // retrieve term information.
548
549 // Information dropped here is expected to be recoverable by
550 // device probing after mastership change
551
552 return Collections.emptyList();
553 }
554 log.debug("timestamp for {} {}", deviceId, newTimestamp);
555
556 final Timestamped<List<PortDescription>> timestampedInput
557 = new Timestamped<>(portDescriptions, newTimestamp);
558 final Timestamped<List<PortDescription>> merged;
559
560 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
561
562 synchronized (device) {
563 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
564 final DeviceDescriptions descs = device.get(providerId);
565 List<PortDescription> mergedList =
566 FluentIterable.from(portDescriptions)
Sho SHIMIZU74626412015-09-11 11:46:27 -0700567 .transform(input ->
568 // lookup merged port description
569 descs.getPortDesc(input.portNumber()).value()
570 ).toList();
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700571 merged = new Timestamped<>(mergedList, newTimestamp);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800572 }
573
574 if (!deviceEvents.isEmpty()) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700575 log.debug("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700576 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800577 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
578 }
579
580 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800581 // Only forward for ConfigProvider
582 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800583 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta89461772016-01-26 12:18:10 -0800584 return Collections.emptyList();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800585 }
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800586 // FIXME Temporary hack for NPE (ONOS-1171).
587 // Proper fix is to implement forwarding to master on ConfigProvider
588 // redo ONOS-490
589 if (deviceNode == null) {
590 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800591 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800592 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800593
594 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800595
596 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700597 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800598 /* error log:
599 log.warn("Failed to process injected ports of device id: {} " +
600 "(cluster messaging failed: {})",
601 deviceId, e);
602 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700603 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700604
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800605 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700606 }
607
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700608 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700609 DeviceId deviceId,
610 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700611
612 Device device = devices.get(deviceId);
613 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
614
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700615 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700616 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
617
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700618 List<DeviceEvent> events = new ArrayList<>();
619 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700620
621 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
622 log.debug("Ignoring outdated events: {}", portDescriptions);
Sho SHIMIZU7b7eabc2015-06-10 20:30:19 -0700623 return Collections.emptyList();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700624 }
625
626 DeviceDescriptions descs = descsMap.get(providerId);
627 // every provider must provide DeviceDescription.
628 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700629 "Device description for Device ID %s from Provider %s was not found",
630 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700631
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700632 Map<PortNumber, Port> ports = getPortMap(deviceId);
633
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700634 final Timestamp newTimestamp = portDescriptions.timestamp();
635
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700636 // Add new ports
637 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700638 for (PortDescription portDescription : portDescriptions.value()) {
639 final PortNumber number = portDescription.portNumber();
640 processed.add(number);
641
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700642 final Port oldPort = ports.get(number);
643 final Port newPort;
644
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700645
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700646 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
647 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700648 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700649 // on new port or valid update
650 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700651 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700652 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700653 newPort = composePort(device, number, descsMap);
654 } else {
655 // outdated event, ignored.
656 continue;
657 }
658
659 events.add(oldPort == null ?
660 createPort(device, newPort, ports) :
661 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700662 }
663
664 events.addAll(pruneOldPorts(device, ports, processed));
665 }
666 return FluentIterable.from(events).filter(notNull()).toList();
667 }
668
669 // Creates a new port based on the port description adds it to the map and
670 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700671 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700672 private DeviceEvent createPort(Device device, Port newPort,
673 Map<PortNumber, Port> ports) {
674 ports.put(newPort.number(), newPort);
675 return new DeviceEvent(PORT_ADDED, device, newPort);
676 }
677
678 // Checks if the specified port requires update and if so, it replaces the
679 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700680 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700681 private DeviceEvent updatePort(Device device, Port oldPort,
682 Port newPort,
683 Map<PortNumber, Port> ports) {
684 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700685 oldPort.type() != newPort.type() ||
686 oldPort.portSpeed() != newPort.portSpeed() ||
687 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700688 ports.put(oldPort.number(), newPort);
689 return new DeviceEvent(PORT_UPDATED, device, newPort);
690 }
691 return null;
692 }
693
694 // Prunes the specified list of ports based on which ports are in the
695 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700696 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700697 private List<DeviceEvent> pruneOldPorts(Device device,
698 Map<PortNumber, Port> ports,
699 Set<PortNumber> processed) {
700 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700701 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700702 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700703 Entry<PortNumber, Port> e = iterator.next();
704 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700705 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700706 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700707 iterator.remove();
708 }
709 }
710 return events;
711 }
712
713 // Gets the map of ports for the specified device; if one does not already
714 // exist, it creates and registers a new one.
715 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
716 return createIfAbsentUnchecked(devicePorts, deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700717 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700718 }
719
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700720 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700721 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700722 Map<ProviderId, DeviceDescriptions> r;
723 r = deviceDescs.get(deviceId);
724 if (r == null) {
Sho SHIMIZUa0fda212015-06-10 19:15:38 -0700725 r = new HashMap<>();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700726 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
727 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
728 if (concurrentlyAdded != null) {
729 r = concurrentlyAdded;
730 }
731 }
732 return r;
733 }
734
735 // Guarded by deviceDescs value (=Device lock)
736 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
737 Map<ProviderId, DeviceDescriptions> device,
738 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700739 synchronized (device) {
740 DeviceDescriptions r = device.get(providerId);
741 if (r == null) {
742 r = new DeviceDescriptions(deltaDesc);
743 device.put(providerId, r);
744 }
745 return r;
746 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700747 }
748
749 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700750 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
751 DeviceId deviceId,
752 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700753 final Timestamp newTimestamp;
754 try {
755 newTimestamp = deviceClockService.getTimestamp(deviceId);
756 } catch (IllegalStateException e) {
757 log.info("Timestamp was not available for device {}", deviceId);
758 log.debug(" discarding {}", portDescription);
759 // Failed to generate timestamp. Ignoring.
760 // See updatePorts comment
761 return null;
762 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700763 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700764 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700765 final DeviceEvent event;
766 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800767 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
768 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700769 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800770 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700771 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700772 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700773 if (event != null) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700774 log.debug("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700775 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800776 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700777 }
778 return event;
779 }
780
781 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700782 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700783 Device device = devices.get(deviceId);
784 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
785
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700786 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700787 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
788
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700789 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700790
791 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
792 log.debug("Ignoring outdated event: {}", deltaDesc);
793 return null;
794 }
795
796 DeviceDescriptions descs = descsMap.get(providerId);
797 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700798 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700799 "Device description for Device ID %s from Provider %s was not found",
800 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700801
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700802 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
803 final PortNumber number = deltaDesc.value().portNumber();
804 final Port oldPort = ports.get(number);
805 final Port newPort;
806
807 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
808 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700809 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700810 // on new port or valid update
811 // update description
812 descs.putPortDesc(deltaDesc);
813 newPort = composePort(device, number, descsMap);
814 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700815 // same or outdated event, ignored.
816 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700817 return null;
818 }
819
820 if (oldPort == null) {
821 return createPort(device, newPort, ports);
822 } else {
823 return updatePort(device, oldPort, newPort, ports);
824 }
825 }
826 }
827
828 @Override
829 public List<Port> getPorts(DeviceId deviceId) {
830 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
831 if (ports == null) {
832 return Collections.emptyList();
833 }
834 return ImmutableList.copyOf(ports.values());
835 }
836
837 @Override
sangho538108b2015-04-08 14:29:20 -0700838 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200839 Collection<PortStatistics> newStatsCollection) {
sangho538108b2015-04-08 14:29:20 -0700840
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200841 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
842 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
843 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
844
845 if (prvStatsMap != null) {
846 for (PortStatistics newStats : newStatsCollection) {
847 PortNumber port = PortNumber.portNumber(newStats.port());
848 PortStatistics prvStats = prvStatsMap.get(port);
849 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
850 PortStatistics deltaStats = builder.build();
851 if (prvStats != null) {
852 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
853 }
854 deltaStatsMap.put(port, deltaStats);
855 newStatsMap.put(port, newStats);
856 }
857 } else {
858 for (PortStatistics newStats : newStatsCollection) {
859 PortNumber port = PortNumber.portNumber(newStats.port());
860 newStatsMap.put(port, newStats);
861 }
sangho538108b2015-04-08 14:29:20 -0700862 }
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200863 devicePortDeltaStats.put(deviceId, deltaStatsMap);
864 devicePortStats.put(deviceId, newStatsMap);
Dusan Pajin517e2232015-08-24 16:50:11 +0200865 // DeviceEvent returns null because of InternalPortStatsListener usage
866 return null;
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200867 }
868
869 /**
870 * Calculate delta statistics by subtracting previous from new statistics.
871 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700872 * @param deviceId device identifier
873 * @param prvStats previous port statistics
874 * @param newStats new port statistics
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200875 * @return PortStatistics
876 */
877 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
878 // calculate time difference
879 long deltaStatsSec, deltaStatsNano;
880 if (newStats.durationNano() < prvStats.durationNano()) {
881 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
882 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
883 } else {
884 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
885 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
886 }
887 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
888 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
889 .setPort(newStats.port())
890 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
891 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
892 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
893 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
894 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
895 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
896 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
897 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
898 .setDurationSec(deltaStatsSec)
899 .setDurationNano(deltaStatsNano)
900 .build();
901 return deltaStats;
sangho538108b2015-04-08 14:29:20 -0700902 }
903
904 @Override
905 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700906 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
907 if (portStats == null) {
908 return Collections.emptyList();
909 }
910 return ImmutableList.copyOf(portStats.values());
911 }
912
913 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200914 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
915 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
916 if (portStats == null) {
917 return Collections.emptyList();
918 }
919 return ImmutableList.copyOf(portStats.values());
920 }
921
922 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700923 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
924 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
925 return ports == null ? null : ports.get(portNumber);
926 }
927
928 @Override
929 public boolean isAvailable(DeviceId deviceId) {
930 return availableDevices.contains(deviceId);
931 }
932
933 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700934 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800935 final NodeId myId = clusterService.getLocalNode().id();
936 NodeId master = mastershipService.getMasterFor(deviceId);
937
938 // if there exist a master, forward
939 // if there is no master, try to become one and process
940
941 boolean relinquishAtEnd = false;
942 if (master == null) {
943 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
944 if (myRole != MastershipRole.NONE) {
945 relinquishAtEnd = true;
946 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800947 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800948 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800949 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700950 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800951 master = myId;
952 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700953 }
954
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800955 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800956 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700957 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800958
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800959 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700960 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800961 /* error log:
962 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
963 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800964
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800965 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700966 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800967 }
968
969 // I have control..
970
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700971 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700972 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700973 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800974 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700975 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800976 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700977 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800978 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800979 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800980 mastershipService.relinquishMastership(deviceId);
981 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700982 return event;
983 }
984
985 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
986 Timestamp timestamp) {
987
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700988 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700989 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700990 // accept removal request if given timestamp is newer than
991 // the latest Timestamp from Primary provider
992 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
Thomas Vachuska710293f2015-11-13 12:29:31 -0800993 if (primDescs == null) {
994 return null;
995 }
996
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700997 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
998 if (timestamp.compareTo(lastTimestamp) <= 0) {
999 // outdated event ignore
1000 return null;
1001 }
1002 removalRequest.put(deviceId, timestamp);
1003
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001004 Device device = devices.remove(deviceId);
1005 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001006 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
1007 if (ports != null) {
1008 ports.clear();
1009 }
1010 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001011 descs.clear();
1012 return device == null ? null :
Dusan Pajin11ff4a82015-08-20 18:03:05 +02001013 new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -07001014 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001015 }
1016
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001017 /**
1018 * Checks if given timestamp is superseded by removal request
1019 * with more recent timestamp.
1020 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001021 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001022 * @param timestampToCheck timestamp of an event to check
1023 * @return true if device is already removed
1024 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001025 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
1026 Timestamp removalTimestamp = removalRequest.get(deviceId);
1027 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001028 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001029 // removalRequest is more recent
1030 return true;
1031 }
1032 return false;
1033 }
1034
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001035 /**
1036 * Returns a Device, merging description given from multiple Providers.
1037 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001038 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001039 * @param providerDescs Collection of Descriptions from multiple providers
1040 * @return Device instance
1041 */
1042 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001043 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001044
Thomas Vachuska444eda62014-10-28 13:09:42 -07001045 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001046
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001047 ProviderId primary = pickPrimaryPid(providerDescs);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001048
1049 DeviceDescriptions desc = providerDescs.get(primary);
1050
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001051 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001052 Type type = base.type();
1053 String manufacturer = base.manufacturer();
1054 String hwVersion = base.hwVersion();
1055 String swVersion = base.swVersion();
1056 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -07001057 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001058 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1059 annotations = merge(annotations, base.annotations());
1060
1061 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1062 if (e.getKey().equals(primary)) {
1063 continue;
1064 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001065 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001066 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001067 // Currently assuming there will never be a key conflict between
1068 // providers
1069
1070 // annotation merging. not so efficient, should revisit later
1071 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1072 }
1073
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001074 return new DefaultDevice(primary, deviceId, type, manufacturer,
1075 hwVersion, swVersion, serialNumber,
1076 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001077 }
1078
Marc De Leenheer88194c32015-05-29 22:10:59 -07001079 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
1080 PortDescription description, Annotations annotations) {
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001081 // FIXME this switch need to go away once all ports are done.
Marc De Leenheer88194c32015-05-29 22:10:59 -07001082 switch (description.type()) {
1083 case OMS:
HIGUCHI Yuta95d83e82016-04-26 12:13:48 -07001084 if (description instanceof OmsPortDescription) {
1085 // remove if-block once deprecation is complete
1086 OmsPortDescription omsDesc = (OmsPortDescription) description;
1087 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
1088 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
1089 }
1090 // same as default
1091 return new DefaultPort(device, number, isEnabled, description.type(),
1092 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001093 case OCH:
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -08001094 if (description instanceof OchPortDescription) {
1095 // remove if-block once Och deprecation is complete
1096 OchPortDescription ochDesc = (OchPortDescription) description;
1097 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
1098 ochDesc.isTunable(), ochDesc.lambda(), annotations);
1099 }
1100 return new DefaultPort(device, number, isEnabled, description.type(),
1101 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001102 case ODUCLT:
HIGUCHI Yuta4c0ef6b2016-05-02 19:45:41 -07001103 if (description instanceof OduCltPortDescription) {
1104 // remove if-block once deprecation is complete
1105 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
1106 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
1107 }
1108 // same as default
1109 return new DefaultPort(device, number, isEnabled, description.type(),
1110 description.portSpeed(), annotations);
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +02001111 case OTU:
HIGUCHI Yuta5be3e822016-05-03 13:51:42 -07001112 if (description instanceof OtuPortDescription) {
1113 // remove if-block once deprecation is complete
1114 OtuPortDescription otuDesc = (OtuPortDescription) description;
1115 return new OtuPort(device, number, isEnabled, otuDesc.signalType(), annotations);
1116 }
1117 // same as default
1118 return new DefaultPort(device, number, isEnabled, description.type(),
1119 description.portSpeed(), annotations);
Marc De Leenheer88194c32015-05-29 22:10:59 -07001120 default:
1121 return new DefaultPort(device, number, isEnabled, description.type(),
1122 description.portSpeed(), annotations);
1123 }
1124 }
1125
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001126 /**
1127 * Returns a Port, merging description given from multiple Providers.
1128 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001129 * @param device device the port is on
1130 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001131 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001132 * @return Port instance
1133 */
1134 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001135 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001136
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001137 ProviderId primary = pickPrimaryPid(descsMap);
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001138 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001139 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001140 boolean isEnabled = false;
1141 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001142 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001143 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1144 if (portDesc != null) {
1145 isEnabled = portDesc.value().isEnabled();
1146 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001147 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001148 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001149 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001150 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001151 if (e.getKey().equals(primary)) {
1152 continue;
1153 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001154 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001155 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001156 // Currently assuming there will never be a key conflict between
1157 // providers
1158
1159 // annotation merging. not so efficient, should revisit later
1160 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1161 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001162 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1163 continue;
1164 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001165 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001166 PortDescription other = otherPortDesc.value();
Marc De Leenheer88194c32015-05-29 22:10:59 -07001167 updated = buildTypedPort(device, number, isEnabled, other, annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001168 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001169 }
1170 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001171 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001172 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001173 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001174 PortDescription current = portDesc.value();
1175 return updated == null
Marc De Leenheer88194c32015-05-29 22:10:59 -07001176 ? buildTypedPort(device, number, isEnabled, current, annotations)
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001177 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001178 }
1179
1180 /**
1181 * @return primary ProviderID, or randomly chosen one if none exists
1182 */
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001183 private ProviderId pickPrimaryPid(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001184 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001185 ProviderId fallBackPrimary = null;
1186 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1187 if (!e.getKey().isAncillary()) {
1188 return e.getKey();
1189 } else if (fallBackPrimary == null) {
1190 // pick randomly as a fallback in case there is no primary
1191 fallBackPrimary = e.getKey();
1192 }
1193 }
1194 return fallBackPrimary;
1195 }
1196
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001197 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001198 Map<ProviderId, DeviceDescriptions> providerDescs) {
Jonathan Hartd9df7bd2015-11-10 17:10:25 -08001199 ProviderId pid = pickPrimaryPid(providerDescs);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001200 return providerDescs.get(pid);
1201 }
1202
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001203 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001204 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001205 }
1206
Jonathan Hart7d656f42015-01-27 14:07:23 -08001207 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001208 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001209 }
Madan Jampani47c93732014-10-06 20:46:08 -07001210
Jonathan Hart7d656f42015-01-27 14:07:23 -08001211 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001212 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001213 }
1214
Jonathan Hart7d656f42015-01-27 14:07:23 -08001215 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001216 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001217 }
1218
Jonathan Hart7d656f42015-01-27 14:07:23 -08001219 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001220 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001221 }
1222
Jonathan Hart7d656f42015-01-27 14:07:23 -08001223 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001224 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001225 }
1226
Jonathan Hart7d656f42015-01-27 14:07:23 -08001227 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001228 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1229 }
1230
1231 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1232 try {
1233 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1234 } catch (IOException e) {
1235 log.error("Failed to send" + event + " to " + recipient, e);
1236 }
1237 }
1238
1239 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1240 try {
1241 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1242 } catch (IOException e) {
1243 log.error("Failed to send" + event + " to " + recipient, e);
1244 }
1245 }
1246
1247 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1248 try {
1249 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1250 } catch (IOException e) {
1251 log.error("Failed to send" + event + " to " + recipient, e);
1252 }
1253 }
1254
1255 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1256 try {
1257 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1258 } catch (IOException e) {
1259 log.error("Failed to send" + event + " to " + recipient, e);
1260 }
1261 }
1262
1263 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1264 try {
1265 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1266 } catch (IOException e) {
1267 log.error("Failed to send" + event + " to " + recipient, e);
1268 }
1269 }
1270
1271 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1272 final NodeId self = clusterService.getLocalNode().id();
1273
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001274 final int numDevices = deviceDescs.size();
1275 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1276 final int portsPerDevice = 8; // random factor to minimize reallocation
1277 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1278 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001279
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001280 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001281
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001282 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001283 synchronized (devDescs) {
1284
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001285 // send device offline timestamp
1286 Timestamp lOffline = this.offline.get(deviceId);
1287 if (lOffline != null) {
1288 adOffline.put(deviceId, lOffline);
1289 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001290
1291 for (Entry<ProviderId, DeviceDescriptions>
1292 prov : devDescs.entrySet()) {
1293
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001294 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001295 final ProviderId provId = prov.getKey();
1296 final DeviceDescriptions descs = prov.getValue();
1297
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001298 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001299 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001300
1301 for (Entry<PortNumber, Timestamped<PortDescription>>
1302 portDesc : descs.getPortDescs().entrySet()) {
1303
1304 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001305 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001306 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001307 }
1308 }
1309 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001310 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001311
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001312 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001313 }
1314
1315 /**
1316 * Responds to anti-entropy advertisement message.
HIGUCHI Yuta67023a22016-03-28 13:35:44 -07001317 * <p>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001318 * Notify sender about out-dated information using regular replication message.
1319 * Send back advertisement to sender if not in sync.
1320 *
1321 * @param advertisement to respond to
1322 */
1323 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1324
1325 final NodeId sender = advertisement.sender();
1326
1327 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1328 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1329 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1330
1331 // Fragments to request
1332 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1333 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1334
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001335 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001336 final DeviceId deviceId = de.getKey();
1337 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1338
1339 synchronized (lDevice) {
1340 // latestTimestamp across provider
1341 // Note: can be null initially
1342 Timestamp localLatest = offline.get(deviceId);
1343
1344 // handle device Ads
1345 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1346 final ProviderId provId = prov.getKey();
1347 final DeviceDescriptions lDeviceDescs = prov.getValue();
1348
1349 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1350
1351
1352 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1353 Timestamp advDevTimestamp = devAds.get(devFragId);
1354
Jonathan Hart403ea932015-02-20 16:23:00 -08001355 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1356 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001357 // remote does not have it or outdated, suggest
1358 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1359 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1360 // local is outdated, request
1361 reqDevices.add(devFragId);
1362 }
1363
1364 // handle port Ads
1365 for (Entry<PortNumber, Timestamped<PortDescription>>
1366 pe : lDeviceDescs.getPortDescs().entrySet()) {
1367
1368 final PortNumber num = pe.getKey();
1369 final Timestamped<PortDescription> lPort = pe.getValue();
1370
1371 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1372
1373 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001374 if (advPortTimestamp == null || lPort.isNewerThan(
1375 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001376 // remote does not have it or outdated, suggest
1377 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1378 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1379 // local is outdated, request
1380 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1381 reqPorts.add(portFragId);
1382 }
1383
1384 // remove port Ad already processed
1385 portAds.remove(portFragId);
1386 } // end local port loop
1387
1388 // remove device Ad already processed
1389 devAds.remove(devFragId);
1390
1391 // find latest and update
1392 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1393 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001394 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001395 localLatest = providerLatest;
1396 }
1397 } // end local provider loop
1398
1399 // checking if remote timestamp is more recent.
1400 Timestamp rOffline = offlineAds.get(deviceId);
1401 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001402 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001403 // remote offline timestamp suggests that the
1404 // device is off-line
1405 markOfflineInternal(deviceId, rOffline);
1406 }
1407
1408 Timestamp lOffline = offline.get(deviceId);
1409 if (lOffline != null && rOffline == null) {
1410 // locally offline, but remote is online, suggest offline
1411 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1412 }
1413
1414 // remove device offline Ad already processed
1415 offlineAds.remove(deviceId);
1416 } // end local device loop
1417 } // device lock
1418
1419 // If there is any Ads left, request them
1420 log.trace("Ads left {}, {}", devAds, portAds);
1421 reqDevices.addAll(devAds.keySet());
1422 reqPorts.addAll(portAds.keySet());
1423
1424 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1425 log.trace("Nothing to request to remote peer {}", sender);
1426 return;
1427 }
1428
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001429 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001430
1431 // 2-way Anti-Entropy for now
1432 try {
1433 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1434 } catch (IOException e) {
1435 log.error("Failed to send response advertisement to " + sender, e);
1436 }
1437
1438// Sketch of 3-way Anti-Entropy
1439// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1440// ClusterMessage message = new ClusterMessage(
1441// clusterService.getLocalNode().id(),
1442// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1443// SERIALIZER.encode(request));
1444//
1445// try {
1446// clusterCommunicator.unicast(message, advertisement.sender());
1447// } catch (IOException e) {
1448// log.error("Failed to send advertisement reply to "
1449// + advertisement.sender(), e);
1450// }
Madan Jampani47c93732014-10-06 20:46:08 -07001451 }
1452
Madan Jampani255a58b2014-10-09 12:08:20 -07001453 private void notifyDelegateIfNotNull(DeviceEvent event) {
1454 if (event != null) {
1455 notifyDelegate(event);
1456 }
1457 }
1458
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001459 private final class SendAdvertisementTask implements Runnable {
1460
1461 @Override
1462 public void run() {
1463 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001464 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001465 return;
1466 }
1467
1468 try {
1469 final NodeId self = clusterService.getLocalNode().id();
1470 Set<ControllerNode> nodes = clusterService.getNodes();
1471
1472 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1473 .transform(toNodeId())
1474 .toList();
1475
1476 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001477 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001478 return;
1479 }
1480
1481 NodeId peer;
1482 do {
1483 int idx = RandomUtils.nextInt(0, nodeIds.size());
1484 peer = nodeIds.get(idx);
1485 } while (peer.equals(self));
1486
1487 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1488
1489 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001490 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001491 return;
1492 }
1493
1494 try {
1495 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1496 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001497 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001498 return;
1499 }
1500 } catch (Exception e) {
1501 // catch all Exception to avoid Scheduled task being suppressed.
1502 log.error("Exception thrown while sending advertisement", e);
1503 }
1504 }
1505 }
1506
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001507 private final class InternalDeviceEventListener
1508 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001509 @Override
1510 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001511 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001512 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001513
Madan Jampani47c93732014-10-06 20:46:08 -07001514 ProviderId providerId = event.providerId();
1515 DeviceId deviceId = event.deviceId();
1516 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001517
Madan Jampani2af244a2015-02-22 13:12:01 -08001518 try {
1519 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1520 } catch (Exception e) {
1521 log.warn("Exception thrown handling device update", e);
1522 }
Madan Jampani47c93732014-10-06 20:46:08 -07001523 }
1524 }
1525
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001526 private final class InternalDeviceOfflineEventListener
1527 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001528 @Override
1529 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001530 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001531 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001532
1533 DeviceId deviceId = event.deviceId();
1534 Timestamp timestamp = event.timestamp();
1535
Madan Jampani2af244a2015-02-22 13:12:01 -08001536 try {
1537 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1538 } catch (Exception e) {
1539 log.warn("Exception thrown handling device offline", e);
1540 }
Madan Jampani25322532014-10-08 11:20:38 -07001541 }
1542 }
1543
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001544 private final class InternalRemoveRequestListener
1545 implements ClusterMessageHandler {
1546 @Override
1547 public void handle(ClusterMessage message) {
1548 log.debug("Received device remove request from peer: {}", message.sender());
1549 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001550
Madan Jampani2af244a2015-02-22 13:12:01 -08001551 try {
1552 removeDevice(did);
1553 } catch (Exception e) {
1554 log.warn("Exception thrown handling device remove", e);
1555 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001556 }
1557 }
1558
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001559 private final class InternalDeviceRemovedEventListener
1560 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001561 @Override
1562 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001563 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001564 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001565
1566 DeviceId deviceId = event.deviceId();
1567 Timestamp timestamp = event.timestamp();
1568
Madan Jampani2af244a2015-02-22 13:12:01 -08001569 try {
1570 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1571 } catch (Exception e) {
1572 log.warn("Exception thrown handling device removed", e);
1573 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001574 }
1575 }
1576
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001577 private final class InternalPortEventListener
1578 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001579 @Override
1580 public void handle(ClusterMessage message) {
1581
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001582 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001583 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001584
1585 ProviderId providerId = event.providerId();
1586 DeviceId deviceId = event.deviceId();
1587 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1588
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001589 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001590 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001591 // Note: dropped information will be recovered by anti-entropy
1592 return;
1593 }
1594
Madan Jampani2af244a2015-02-22 13:12:01 -08001595 try {
1596 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1597 } catch (Exception e) {
1598 log.warn("Exception thrown handling port update", e);
1599 }
Madan Jampani47c93732014-10-06 20:46:08 -07001600 }
1601 }
1602
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001603 private final class InternalPortStatusEventListener
1604 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001605 @Override
1606 public void handle(ClusterMessage message) {
1607
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001608 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001609 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001610
1611 ProviderId providerId = event.providerId();
1612 DeviceId deviceId = event.deviceId();
1613 Timestamped<PortDescription> portDescription = event.portDescription();
1614
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001615 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001616 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001617 // Note: dropped information will be recovered by anti-entropy
1618 return;
1619 }
1620
Madan Jampani2af244a2015-02-22 13:12:01 -08001621 try {
1622 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1623 } catch (Exception e) {
1624 log.warn("Exception thrown handling port update", e);
1625 }
Madan Jampani47c93732014-10-06 20:46:08 -07001626 }
1627 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001628
1629 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001630 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001631 @Override
1632 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001633 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001634 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001635 try {
1636 handleAdvertisement(advertisement);
1637 } catch (Exception e) {
1638 log.warn("Exception thrown handling Device advertisements.", e);
1639 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001640 }
1641 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001642
1643 private final class DeviceInjectedEventListener
1644 implements ClusterMessageHandler {
1645 @Override
1646 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001647 log.debug("Received injected device event from peer: {}", message.sender());
1648 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1649
1650 ProviderId providerId = event.providerId();
1651 DeviceId deviceId = event.deviceId();
1652 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001653 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1654 // workaround for ONOS-1208
1655 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1656 return;
1657 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001658
Madan Jampani2af244a2015-02-22 13:12:01 -08001659 try {
1660 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1661 } catch (Exception e) {
1662 log.warn("Exception thrown handling device injected event.", e);
1663 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001664 }
1665 }
1666
1667 private final class PortInjectedEventListener
1668 implements ClusterMessageHandler {
1669 @Override
1670 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001671 log.debug("Received injected port event from peer: {}", message.sender());
1672 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1673
1674 ProviderId providerId = event.providerId();
1675 DeviceId deviceId = event.deviceId();
1676 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001677 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1678 // workaround for ONOS-1208
1679 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1680 return;
1681 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001682
Madan Jampani2af244a2015-02-22 13:12:01 -08001683 try {
1684 updatePorts(providerId, deviceId, portDescriptions);
1685 } catch (Exception e) {
1686 log.warn("Exception thrown handling port injected event.", e);
1687 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001688 }
1689 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001690
1691 private class InternalPortStatsListener
1692 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1693 @Override
1694 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1695 if (event.type() == PUT) {
1696 Device device = devices.get(event.key());
1697 if (device != null) {
1698 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1699 }
1700 }
1701 }
1702 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001703}