blob: 5ea27af43a84a7bd3c5f29f3ab1a4fa059dc7656 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 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
Yuta HIGUCHI47c40882014-10-10 18:44:37 -070018import com.google.common.base.Function;
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -080019import com.google.common.base.Predicate;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070020import com.google.common.collect.FluentIterable;
21import com.google.common.collect.ImmutableList;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -070022import com.google.common.collect.Maps;
23import com.google.common.collect.Sets;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070024import org.apache.commons.lang3.RandomUtils;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070025import org.apache.felix.scr.annotations.Activate;
26import org.apache.felix.scr.annotations.Component;
27import org.apache.felix.scr.annotations.Deactivate;
28import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
30import org.apache.felix.scr.annotations.Service;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080031import org.onlab.packet.ChassisId;
32import org.onlab.util.KryoNamespace;
33import org.onlab.util.NewConcurrentHashMap;
Brian O'Connorabafb502014-12-02 22:26:20 -080034import org.onosproject.cluster.ClusterService;
35import org.onosproject.cluster.ControllerNode;
36import org.onosproject.cluster.NodeId;
37import org.onosproject.mastership.MastershipService;
38import org.onosproject.mastership.MastershipTerm;
39import org.onosproject.mastership.MastershipTermService;
40import 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;
Brian O'Connorabafb502014-12-02 22:26:20 -080051import org.onosproject.net.Port;
52import org.onosproject.net.PortNumber;
53import 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;
Brian O'Connorabafb502014-12-02 22:26:20 -080061import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070062import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080063import org.onosproject.net.provider.ProviderId;
64import org.onosproject.store.AbstractStore;
65import org.onosproject.store.Timestamp;
66import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
67import org.onosproject.store.cluster.messaging.ClusterMessage;
68import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
69import org.onosproject.store.cluster.messaging.MessageSubject;
70import org.onosproject.store.impl.Timestamped;
71import org.onosproject.store.serializers.KryoSerializer;
Brian O'Connor6de2e202015-05-21 14:30:41 -070072import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070073import org.slf4j.Logger;
74
Madan Jampani47c93732014-10-06 20:46:08 -070075import java.io.IOException;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070076import java.util.ArrayList;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070077import java.util.Collection;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070078import java.util.Collections;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070079import java.util.HashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070080import java.util.HashSet;
81import java.util.Iterator;
82import java.util.List;
83import java.util.Map;
84import java.util.Map.Entry;
85import java.util.Objects;
86import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070087import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080088import java.util.concurrent.ExecutorService;
89import java.util.concurrent.Executors;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070090import java.util.concurrent.ScheduledExecutorService;
91import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070092
93import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070094import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070095import static com.google.common.base.Verify.verify;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -080096import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
97import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080098import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -080099import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800100import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
101import static org.onosproject.net.DefaultAnnotations.merge;
102import static org.onosproject.net.device.DeviceEvent.Type.*;
103import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
104import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
105import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700106
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700107/**
108 * Manages inventory of infrastructure devices using gossip protocol to distribute
109 * information.
110 */
111@Component(immediate = true)
112@Service
113public class GossipDeviceStore
114 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
115 implements DeviceStore {
116
117 private final Logger log = getLogger(getClass());
118
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700119 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800120 // Timeout in milliseconds to process device or ports on remote master node
121 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700122
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700123 // innerMap is used to lock a Device, thus instance should never be replaced.
124 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700125 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700126 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700127
128 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700129 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
130 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
sangho538108b2015-04-08 14:29:20 -0700131 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, PortStatistics>>
132 devicePortStats = Maps.newConcurrentMap();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700133
134 // to be updated under Device lock
135 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
136 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700137
138 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700139 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700140
141 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700142 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700143
Madan Jampani47c93732014-10-06 20:46:08 -0700144 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
145 protected ClusterCommunicationService clusterCommunicator;
146
Madan Jampani53e44e62014-10-07 12:39:51 -0700147 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
148 protected ClusterService clusterService;
149
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700150 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
151 protected MastershipService mastershipService;
152
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800153 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
154 protected MastershipTermService termService;
155
156
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700157 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700158 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700159 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700160 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800161 .register(DistributedStoreSerializers.STORE_COMMON)
162 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
163 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
164 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700165 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800166 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
167 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700168 .register(DeviceAntiEntropyAdvertisement.class)
169 .register(DeviceFragmentId.class)
170 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800171 .register(DeviceInjectedEvent.class)
172 .register(PortInjectedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800173 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700174 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700175 };
176
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800177 private ExecutorService executor;
178
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800179 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700180
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800181 // TODO make these anti-entropy parameters configurable
182 private long initialDelaySec = 5;
183 private long periodSec = 5;
184
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800185
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700186 @Activate
187 public void activate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700188
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800189 executor = Executors.newCachedThreadPool(groupedThreads("onos/device", "fg-%d"));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800190
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800191 backgroundExecutor =
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800192 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700193
Madan Jampani2af244a2015-02-22 13:12:01 -0800194 clusterCommunicator.addSubscriber(
195 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
196 clusterCommunicator.addSubscriber(
197 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
198 new InternalDeviceOfflineEventListener(),
199 executor);
200 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
201 new InternalRemoveRequestListener(),
202 executor);
203 clusterCommunicator.addSubscriber(
204 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
205 clusterCommunicator.addSubscriber(
206 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
207 clusterCommunicator.addSubscriber(
208 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
209 clusterCommunicator.addSubscriber(
210 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
211 new InternalDeviceAdvertisementListener(),
212 backgroundExecutor);
213 clusterCommunicator.addSubscriber(
214 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
215 clusterCommunicator.addSubscriber(
216 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
217
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700218 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800219 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Marc De Leenheer4b18a232015-04-30 11:58:20 -0700220 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700221
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700222 log.info("Started");
223 }
224
225 @Deactivate
226 public void deactivate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700227
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800228 executor.shutdownNow();
229
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800230 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700231 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800232 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700233 log.error("Timeout during executor shutdown");
234 }
235 } catch (InterruptedException e) {
236 log.error("Error during executor shutdown", e);
237 }
238
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700239 deviceDescs.clear();
240 devices.clear();
241 devicePorts.clear();
242 availableDevices.clear();
243 log.info("Stopped");
244 }
245
246 @Override
247 public int getDeviceCount() {
248 return devices.size();
249 }
250
251 @Override
252 public Iterable<Device> getDevices() {
253 return Collections.unmodifiableCollection(devices.values());
254 }
255
256 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800257 public Iterable<Device> getAvailableDevices() {
258 return FluentIterable.from(getDevices())
259 .filter(new Predicate<Device>() {
260
261 @Override
262 public boolean apply(Device input) {
263 return isAvailable(input.id());
264 }
265 });
266 }
267
268 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700269 public Device getDevice(DeviceId deviceId) {
270 return devices.get(deviceId);
271 }
272
273 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700274 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
275 DeviceId deviceId,
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700276 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800277 NodeId localNode = clusterService.getLocalNode().id();
278 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
279
280 // Process device update only if we're the master,
281 // otherwise signal the actual master.
282 DeviceEvent deviceEvent = null;
283 if (localNode.equals(deviceNode)) {
284
285 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
286 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
287 final Timestamped<DeviceDescription> mergedDesc;
288 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
289
290 synchronized (device) {
291 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
292 mergedDesc = device.get(providerId).getDeviceDesc();
293 }
294
295 if (deviceEvent != null) {
296 log.info("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
297 providerId, deviceId);
298 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
299 }
300
301 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800302 // FIXME Temporary hack for NPE (ONOS-1171).
303 // Proper fix is to implement forwarding to master on ConfigProvider
304 // redo ONOS-490
305 if (deviceNode == null) {
306 // silently ignore
307 return null;
308 }
309
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800310
311 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
312 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800313
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800314 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700315 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800316 /* error log:
317 log.warn("Failed to process injected device id: {} desc: {} " +
318 "(cluster messaging failed: {})",
319 deviceId, deviceDescription, e);
320 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700321 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800322
323 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700324 }
325
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700326 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
327 DeviceId deviceId,
328 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700329
330 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800331 Map<ProviderId, DeviceDescriptions> device
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700332 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700333
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800334 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700335 // locking per device
336
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700337 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
338 log.debug("Ignoring outdated event: {}", deltaDesc);
339 return null;
340 }
341
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800342 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700343
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700344 final Device oldDevice = devices.get(deviceId);
345 final Device newDevice;
346
347 if (deltaDesc == descs.getDeviceDesc() ||
348 deltaDesc.isNewer(descs.getDeviceDesc())) {
349 // on new device or valid update
350 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800351 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700352 } else {
353 // outdated event, ignored.
354 return null;
355 }
356 if (oldDevice == null) {
357 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700358 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700359 } else {
360 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700361 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700362 }
363 }
364 }
365
366 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700367 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700368 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700369 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700370
371 // update composed device cache
372 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
373 verify(oldDevice == null,
374 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
375 providerId, oldDevice, newDevice);
376
377 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700378 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700379 }
380
381 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
382 }
383
384 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700385 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700386 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700387 Device oldDevice,
388 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700389 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700390 boolean propertiesChanged =
391 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700392 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
393 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700394 boolean annotationsChanged =
395 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700396
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700397 // Primary providers can respond to all changes, but ancillary ones
398 // should respond only to annotation changes.
399 if ((providerId.isAncillary() && annotationsChanged) ||
400 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700401 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
402 if (!replaced) {
403 verify(replaced,
404 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
405 providerId, oldDevice, devices.get(newDevice.id())
406 , newDevice);
407 }
408 if (!providerId.isAncillary()) {
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700409 boolean wasOnline = availableDevices.contains(newDevice.id());
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700410 markOnline(newDevice.id(), newTimestamp);
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700411 if (!wasOnline) {
412 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
413 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700414 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700415
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700416 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700417 }
418 return null;
419 }
420
421 @Override
422 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700423 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700424 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700425 if (event != null) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700426 log.info("Notifying peers of a device offline topology event for deviceId: {} {}",
427 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800428 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700429 }
430 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700431 }
432
433 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
434
435 Map<ProviderId, DeviceDescriptions> providerDescs
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700436 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700437
438 // locking device
439 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700440
441 // accept off-line if given timestamp is newer than
442 // the latest Timestamp from Primary provider
443 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
444 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
445 if (timestamp.compareTo(lastTimestamp) <= 0) {
446 // outdated event ignore
447 return null;
448 }
449
450 offline.put(deviceId, timestamp);
451
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700452 Device device = devices.get(deviceId);
453 if (device == null) {
454 return null;
455 }
456 boolean removed = availableDevices.remove(deviceId);
457 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700458 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700459 }
460 return null;
461 }
462 }
463
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700464 /**
465 * Marks the device as available if the given timestamp is not outdated,
466 * compared to the time the device has been marked offline.
467 *
468 * @param deviceId identifier of the device
469 * @param timestamp of the event triggering this change.
470 * @return true if availability change request was accepted and changed the state
471 */
472 // Guarded by deviceDescs value (=Device lock)
473 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
474 // accept on-line if given timestamp is newer than
475 // the latest offline request Timestamp
476 Timestamp offlineTimestamp = offline.get(deviceId);
477 if (offlineTimestamp == null ||
478 offlineTimestamp.compareTo(timestamp) < 0) {
479
480 offline.remove(deviceId);
481 return availableDevices.add(deviceId);
482 }
483 return false;
484 }
485
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700486 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700487 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
488 DeviceId deviceId,
489 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700490
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800491 NodeId localNode = clusterService.getLocalNode().id();
492 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
493 // since it will trigger distributed store read.
494 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
495 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
496 // If we don't care much about topology performance, then it might be OK.
497 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700498
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800499 // Process port update only if we're the master of the device,
500 // otherwise signal the actual master.
501 List<DeviceEvent> deviceEvents = null;
502 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700503
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800504 final Timestamp newTimestamp;
505 try {
506 newTimestamp = deviceClockService.getTimestamp(deviceId);
507 } catch (IllegalStateException e) {
508 log.info("Timestamp was not available for device {}", deviceId);
509 log.debug(" discarding {}", portDescriptions);
510 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700511
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800512 // Possible situation:
513 // Device connected and became master for short period of time,
514 // but lost mastership before this instance had the chance to
515 // retrieve term information.
516
517 // Information dropped here is expected to be recoverable by
518 // device probing after mastership change
519
520 return Collections.emptyList();
521 }
522 log.debug("timestamp for {} {}", deviceId, newTimestamp);
523
524 final Timestamped<List<PortDescription>> timestampedInput
525 = new Timestamped<>(portDescriptions, newTimestamp);
526 final Timestamped<List<PortDescription>> merged;
527
528 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
529
530 synchronized (device) {
531 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
532 final DeviceDescriptions descs = device.get(providerId);
533 List<PortDescription> mergedList =
534 FluentIterable.from(portDescriptions)
535 .transform(new Function<PortDescription, PortDescription>() {
536 @Override
537 public PortDescription apply(PortDescription input) {
538 // lookup merged port description
539 return descs.getPortDesc(input.portNumber()).value();
540 }
541 }).toList();
542 merged = new Timestamped<List<PortDescription>>(mergedList, newTimestamp);
543 }
544
545 if (!deviceEvents.isEmpty()) {
546 log.info("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
547 providerId, deviceId);
548 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
549 }
550
551 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800552 // FIXME Temporary hack for NPE (ONOS-1171).
553 // Proper fix is to implement forwarding to master on ConfigProvider
554 // redo ONOS-490
555 if (deviceNode == null) {
556 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800557 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800558 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800559
560 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800561
562 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700563 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800564 /* error log:
565 log.warn("Failed to process injected ports of device id: {} " +
566 "(cluster messaging failed: {})",
567 deviceId, e);
568 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700569 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700570
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800571 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700572 }
573
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700574 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
575 DeviceId deviceId,
576 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700577
578 Device device = devices.get(deviceId);
579 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
580
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700581 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700582 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
583
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700584 List<DeviceEvent> events = new ArrayList<>();
585 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700586
587 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
588 log.debug("Ignoring outdated events: {}", portDescriptions);
589 return null;
590 }
591
592 DeviceDescriptions descs = descsMap.get(providerId);
593 // every provider must provide DeviceDescription.
594 checkArgument(descs != null,
595 "Device description for Device ID %s from Provider %s was not found",
596 deviceId, providerId);
597
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700598 Map<PortNumber, Port> ports = getPortMap(deviceId);
599
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700600 final Timestamp newTimestamp = portDescriptions.timestamp();
601
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700602 // Add new ports
603 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700604 for (PortDescription portDescription : portDescriptions.value()) {
605 final PortNumber number = portDescription.portNumber();
606 processed.add(number);
607
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700608 final Port oldPort = ports.get(number);
609 final Port newPort;
610
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700611
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700612 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
613 if (existingPortDesc == null ||
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700614 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700615 // on new port or valid update
616 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700617 descs.putPortDesc(new Timestamped<>(portDescription,
618 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700619 newPort = composePort(device, number, descsMap);
620 } else {
621 // outdated event, ignored.
622 continue;
623 }
624
625 events.add(oldPort == null ?
626 createPort(device, newPort, ports) :
627 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700628 }
629
630 events.addAll(pruneOldPorts(device, ports, processed));
631 }
632 return FluentIterable.from(events).filter(notNull()).toList();
633 }
634
635 // Creates a new port based on the port description adds it to the map and
636 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700637 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700638 private DeviceEvent createPort(Device device, Port newPort,
639 Map<PortNumber, Port> ports) {
640 ports.put(newPort.number(), newPort);
641 return new DeviceEvent(PORT_ADDED, device, newPort);
642 }
643
644 // Checks if the specified port requires update and if so, it replaces the
645 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700646 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700647 private DeviceEvent updatePort(Device device, Port oldPort,
648 Port newPort,
649 Map<PortNumber, Port> ports) {
650 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700651 oldPort.type() != newPort.type() ||
652 oldPort.portSpeed() != newPort.portSpeed() ||
653 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700654 ports.put(oldPort.number(), newPort);
655 return new DeviceEvent(PORT_UPDATED, device, newPort);
656 }
657 return null;
658 }
659
660 // Prunes the specified list of ports based on which ports are in the
661 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700662 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700663 private List<DeviceEvent> pruneOldPorts(Device device,
664 Map<PortNumber, Port> ports,
665 Set<PortNumber> processed) {
666 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700667 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700668 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700669 Entry<PortNumber, Port> e = iterator.next();
670 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700671 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700672 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700673 iterator.remove();
674 }
675 }
676 return events;
677 }
678
679 // Gets the map of ports for the specified device; if one does not already
680 // exist, it creates and registers a new one.
681 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
682 return createIfAbsentUnchecked(devicePorts, deviceId,
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700683 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
684 }
685
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700686 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700687 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700688 Map<ProviderId, DeviceDescriptions> r;
689 r = deviceDescs.get(deviceId);
690 if (r == null) {
691 r = new HashMap<ProviderId, DeviceDescriptions>();
692 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
693 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
694 if (concurrentlyAdded != null) {
695 r = concurrentlyAdded;
696 }
697 }
698 return r;
699 }
700
701 // Guarded by deviceDescs value (=Device lock)
702 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
703 Map<ProviderId, DeviceDescriptions> device,
704 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
705
706 synchronized (device) {
707 DeviceDescriptions r = device.get(providerId);
708 if (r == null) {
709 r = new DeviceDescriptions(deltaDesc);
710 device.put(providerId, r);
711 }
712 return r;
713 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700714 }
715
716 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700717 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
718 DeviceId deviceId,
719 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700720 final Timestamp newTimestamp;
721 try {
722 newTimestamp = deviceClockService.getTimestamp(deviceId);
723 } catch (IllegalStateException e) {
724 log.info("Timestamp was not available for device {}", deviceId);
725 log.debug(" discarding {}", portDescription);
726 // Failed to generate timestamp. Ignoring.
727 // See updatePorts comment
728 return null;
729 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700730 final Timestamped<PortDescription> deltaDesc
731 = new Timestamped<>(portDescription, newTimestamp);
732 final DeviceEvent event;
733 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800734 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
735 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700736 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800737 mergedDesc = device.get(providerId)
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700738 .getPortDesc(portDescription.portNumber());
739 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700740 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700741 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
742 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800743 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700744 }
745 return event;
746 }
747
748 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
749 Timestamped<PortDescription> deltaDesc) {
750
751 Device device = devices.get(deviceId);
752 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
753
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700754 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700755 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
756
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700757 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700758
759 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
760 log.debug("Ignoring outdated event: {}", deltaDesc);
761 return null;
762 }
763
764 DeviceDescriptions descs = descsMap.get(providerId);
765 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700766 verify(descs != null,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700767 "Device description for Device ID %s from Provider %s was not found",
768 deviceId, providerId);
769
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700770 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
771 final PortNumber number = deltaDesc.value().portNumber();
772 final Port oldPort = ports.get(number);
773 final Port newPort;
774
775 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
776 if (existingPortDesc == null ||
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700777 deltaDesc.isNewer(existingPortDesc)) {
778 // on new port or valid update
779 // update description
780 descs.putPortDesc(deltaDesc);
781 newPort = composePort(device, number, descsMap);
782 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700783 // same or outdated event, ignored.
784 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700785 return null;
786 }
787
788 if (oldPort == null) {
789 return createPort(device, newPort, ports);
790 } else {
791 return updatePort(device, oldPort, newPort, ports);
792 }
793 }
794 }
795
796 @Override
797 public List<Port> getPorts(DeviceId deviceId) {
798 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
799 if (ports == null) {
800 return Collections.emptyList();
801 }
802 return ImmutableList.copyOf(ports.values());
803 }
804
805 @Override
sangho538108b2015-04-08 14:29:20 -0700806 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
807 Collection<PortStatistics> portStats) {
808
809 ConcurrentMap<PortNumber, PortStatistics> statsMap = devicePortStats.get(deviceId);
810 if (statsMap == null) {
811 statsMap = Maps.newConcurrentMap();
812 devicePortStats.put(deviceId, statsMap);
813 }
814
815 for (PortStatistics stat: portStats) {
816 PortNumber portNumber = PortNumber.portNumber(stat.port());
817 statsMap.put(portNumber, stat);
818 }
819
820 return new DeviceEvent(PORT_STATS_UPDATED, devices.get(deviceId), null);
821 }
822
823 @Override
824 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
825
826 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
827 if (portStats == null) {
828 return Collections.emptyList();
829 }
830 return ImmutableList.copyOf(portStats.values());
831 }
832
833 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700834 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
835 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
836 return ports == null ? null : ports.get(portNumber);
837 }
838
839 @Override
840 public boolean isAvailable(DeviceId deviceId) {
841 return availableDevices.contains(deviceId);
842 }
843
844 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700845 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800846 final NodeId myId = clusterService.getLocalNode().id();
847 NodeId master = mastershipService.getMasterFor(deviceId);
848
849 // if there exist a master, forward
850 // if there is no master, try to become one and process
851
852 boolean relinquishAtEnd = false;
853 if (master == null) {
854 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
855 if (myRole != MastershipRole.NONE) {
856 relinquishAtEnd = true;
857 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800858 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800859 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800860 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700861 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800862 master = myId;
863 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700864 }
865
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800866 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800867 log.debug("{} has control of {}, forwarding remove request",
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800868 master, deviceId);
869
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800870 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700871 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800872 /* error log:
873 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
874 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800875
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800876 // event will be triggered after master processes it.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800877 return null;
878 }
879
880 // I have control..
881
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700882 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700883 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700884 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800885 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700886 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800887 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700888 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800889 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800890 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800891 mastershipService.relinquishMastership(deviceId);
892 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700893 return event;
894 }
895
896 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
897 Timestamp timestamp) {
898
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700899 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700900 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700901 // accept removal request if given timestamp is newer than
902 // the latest Timestamp from Primary provider
903 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
904 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
905 if (timestamp.compareTo(lastTimestamp) <= 0) {
906 // outdated event ignore
907 return null;
908 }
909 removalRequest.put(deviceId, timestamp);
910
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700911 Device device = devices.remove(deviceId);
912 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700913 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
914 if (ports != null) {
915 ports.clear();
916 }
917 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700918 descs.clear();
919 return device == null ? null :
920 new DeviceEvent(DEVICE_REMOVED, device, null);
921 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700922 }
923
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700924 /**
925 * Checks if given timestamp is superseded by removal request
926 * with more recent timestamp.
927 *
928 * @param deviceId identifier of a device
929 * @param timestampToCheck timestamp of an event to check
930 * @return true if device is already removed
931 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700932 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
933 Timestamp removalTimestamp = removalRequest.get(deviceId);
934 if (removalTimestamp != null &&
935 removalTimestamp.compareTo(timestampToCheck) >= 0) {
936 // removalRequest is more recent
937 return true;
938 }
939 return false;
940 }
941
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700942 /**
943 * Returns a Device, merging description given from multiple Providers.
944 *
945 * @param deviceId device identifier
946 * @param providerDescs Collection of Descriptions from multiple providers
947 * @return Device instance
948 */
949 private Device composeDevice(DeviceId deviceId,
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700950 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700951
Thomas Vachuska444eda62014-10-28 13:09:42 -0700952 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700953
954 ProviderId primary = pickPrimaryPID(providerDescs);
955
956 DeviceDescriptions desc = providerDescs.get(primary);
957
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700958 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700959 Type type = base.type();
960 String manufacturer = base.manufacturer();
961 String hwVersion = base.hwVersion();
962 String swVersion = base.swVersion();
963 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700964 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700965 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
966 annotations = merge(annotations, base.annotations());
967
968 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
969 if (e.getKey().equals(primary)) {
970 continue;
971 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800972 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700973 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700974 // Currently assuming there will never be a key conflict between
975 // providers
976
977 // annotation merging. not so efficient, should revisit later
978 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
979 }
980
981 return new DefaultDevice(primary, deviceId , type, manufacturer,
alshabib7911a052014-10-16 17:49:37 -0700982 hwVersion, swVersion, serialNumber,
983 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700984 }
985
986 /**
987 * Returns a Port, merging description given from multiple Providers.
988 *
989 * @param device device the port is on
990 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700991 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700992 * @return Port instance
993 */
994 private Port composePort(Device device, PortNumber number,
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700995 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700996
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700997 ProviderId primary = pickPrimaryPID(descsMap);
998 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700999 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001000 boolean isEnabled = false;
1001 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001002 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001003 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1004 if (portDesc != null) {
1005 isEnabled = portDesc.value().isEnabled();
1006 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001007 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001008 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001009 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001010 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001011 if (e.getKey().equals(primary)) {
1012 continue;
1013 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001014 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001015 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001016 // Currently assuming there will never be a key conflict between
1017 // providers
1018
1019 // annotation merging. not so efficient, should revisit later
1020 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1021 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001022 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1023 continue;
1024 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001025 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001026 PortDescription other = otherPortDesc.value();
1027 switch (other.type()) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001028 case OMS:
1029 OmsPortDescription omsPortDesc = (OmsPortDescription) otherPortDesc.value();
1030 updated = new OmsPort(device, number, isEnabled, omsPortDesc.minFrequency(),
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001031 omsPortDesc.maxFrequency(), omsPortDesc.grid(), annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001032 break;
1033 case OCH:
1034 OchPortDescription ochPortDesc = (OchPortDescription) otherPortDesc.value();
1035 updated = new OchPort(device, number, isEnabled, ochPortDesc.signalType(),
1036 ochPortDesc.isTunable(), ochPortDesc.lambda(), annotations);
1037 break;
1038 case ODUCLT:
1039 OduCltPortDescription oduCltPortDesc = (OduCltPortDescription) otherPortDesc.value();
1040 updated = new OduCltPort(device, number, isEnabled, oduCltPortDesc.signalType(), annotations);
1041 break;
1042 default:
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001043 updated = new DefaultPort(
1044 device, number, isEnabled, other.type(), other.portSpeed(), annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001045 }
1046 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001047 }
1048 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001049 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001050 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001051 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001052 PortDescription current = portDesc.value();
1053 return updated == null
1054 ? new DefaultPort(device, number, isEnabled, current.type(), current.portSpeed(), annotations)
1055 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001056 }
1057
1058 /**
1059 * @return primary ProviderID, or randomly chosen one if none exists
1060 */
1061 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001062 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001063 ProviderId fallBackPrimary = null;
1064 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1065 if (!e.getKey().isAncillary()) {
1066 return e.getKey();
1067 } else if (fallBackPrimary == null) {
1068 // pick randomly as a fallback in case there is no primary
1069 fallBackPrimary = e.getKey();
1070 }
1071 }
1072 return fallBackPrimary;
1073 }
1074
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001075 private DeviceDescriptions getPrimaryDescriptions(
1076 Map<ProviderId, DeviceDescriptions> providerDescs) {
1077 ProviderId pid = pickPrimaryPID(providerDescs);
1078 return providerDescs.get(pid);
1079 }
1080
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001081 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001082 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001083 }
1084
Jonathan Hart7d656f42015-01-27 14:07:23 -08001085 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001086 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001087 }
Madan Jampani47c93732014-10-06 20:46:08 -07001088
Jonathan Hart7d656f42015-01-27 14:07:23 -08001089 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001090 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001091 }
1092
Jonathan Hart7d656f42015-01-27 14:07:23 -08001093 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001094 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001095 }
1096
Jonathan Hart7d656f42015-01-27 14:07:23 -08001097 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001098 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001099 }
1100
Jonathan Hart7d656f42015-01-27 14:07:23 -08001101 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001102 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001103 }
1104
Jonathan Hart7d656f42015-01-27 14:07:23 -08001105 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001106 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1107 }
1108
1109 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1110 try {
1111 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1112 } catch (IOException e) {
1113 log.error("Failed to send" + event + " to " + recipient, e);
1114 }
1115 }
1116
1117 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1118 try {
1119 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1120 } catch (IOException e) {
1121 log.error("Failed to send" + event + " to " + recipient, e);
1122 }
1123 }
1124
1125 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1126 try {
1127 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1128 } catch (IOException e) {
1129 log.error("Failed to send" + event + " to " + recipient, e);
1130 }
1131 }
1132
1133 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1134 try {
1135 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1136 } catch (IOException e) {
1137 log.error("Failed to send" + event + " to " + recipient, e);
1138 }
1139 }
1140
1141 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1142 try {
1143 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1144 } catch (IOException e) {
1145 log.error("Failed to send" + event + " to " + recipient, e);
1146 }
1147 }
1148
1149 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1150 final NodeId self = clusterService.getLocalNode().id();
1151
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001152 final int numDevices = deviceDescs.size();
1153 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1154 final int portsPerDevice = 8; // random factor to minimize reallocation
1155 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1156 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001157
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001158 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001159
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001160 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001161 synchronized (devDescs) {
1162
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001163 // send device offline timestamp
1164 Timestamp lOffline = this.offline.get(deviceId);
1165 if (lOffline != null) {
1166 adOffline.put(deviceId, lOffline);
1167 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001168
1169 for (Entry<ProviderId, DeviceDescriptions>
1170 prov : devDescs.entrySet()) {
1171
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001172 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001173 final ProviderId provId = prov.getKey();
1174 final DeviceDescriptions descs = prov.getValue();
1175
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001176 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001177 descs.getDeviceDesc().timestamp());
1178
1179 for (Entry<PortNumber, Timestamped<PortDescription>>
1180 portDesc : descs.getPortDescs().entrySet()) {
1181
1182 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001183 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001184 portDesc.getValue().timestamp());
1185 }
1186 }
1187 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001188 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001189
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001190 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001191 }
1192
1193 /**
1194 * Responds to anti-entropy advertisement message.
1195 * <P>
1196 * Notify sender about out-dated information using regular replication message.
1197 * Send back advertisement to sender if not in sync.
1198 *
1199 * @param advertisement to respond to
1200 */
1201 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1202
1203 final NodeId sender = advertisement.sender();
1204
1205 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1206 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1207 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1208
1209 // Fragments to request
1210 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1211 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1212
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001213 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001214 final DeviceId deviceId = de.getKey();
1215 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1216
1217 synchronized (lDevice) {
1218 // latestTimestamp across provider
1219 // Note: can be null initially
1220 Timestamp localLatest = offline.get(deviceId);
1221
1222 // handle device Ads
1223 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1224 final ProviderId provId = prov.getKey();
1225 final DeviceDescriptions lDeviceDescs = prov.getValue();
1226
1227 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1228
1229
1230 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1231 Timestamp advDevTimestamp = devAds.get(devFragId);
1232
Jonathan Hart403ea932015-02-20 16:23:00 -08001233 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1234 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001235 // remote does not have it or outdated, suggest
1236 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1237 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1238 // local is outdated, request
1239 reqDevices.add(devFragId);
1240 }
1241
1242 // handle port Ads
1243 for (Entry<PortNumber, Timestamped<PortDescription>>
1244 pe : lDeviceDescs.getPortDescs().entrySet()) {
1245
1246 final PortNumber num = pe.getKey();
1247 final Timestamped<PortDescription> lPort = pe.getValue();
1248
1249 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1250
1251 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001252 if (advPortTimestamp == null || lPort.isNewerThan(
1253 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001254 // remote does not have it or outdated, suggest
1255 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1256 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1257 // local is outdated, request
1258 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1259 reqPorts.add(portFragId);
1260 }
1261
1262 // remove port Ad already processed
1263 portAds.remove(portFragId);
1264 } // end local port loop
1265
1266 // remove device Ad already processed
1267 devAds.remove(devFragId);
1268
1269 // find latest and update
1270 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1271 if (localLatest == null ||
1272 providerLatest.compareTo(localLatest) > 0) {
1273 localLatest = providerLatest;
1274 }
1275 } // end local provider loop
1276
1277 // checking if remote timestamp is more recent.
1278 Timestamp rOffline = offlineAds.get(deviceId);
1279 if (rOffline != null &&
1280 rOffline.compareTo(localLatest) > 0) {
1281 // remote offline timestamp suggests that the
1282 // device is off-line
1283 markOfflineInternal(deviceId, rOffline);
1284 }
1285
1286 Timestamp lOffline = offline.get(deviceId);
1287 if (lOffline != null && rOffline == null) {
1288 // locally offline, but remote is online, suggest offline
1289 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1290 }
1291
1292 // remove device offline Ad already processed
1293 offlineAds.remove(deviceId);
1294 } // end local device loop
1295 } // device lock
1296
1297 // If there is any Ads left, request them
1298 log.trace("Ads left {}, {}", devAds, portAds);
1299 reqDevices.addAll(devAds.keySet());
1300 reqPorts.addAll(portAds.keySet());
1301
1302 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1303 log.trace("Nothing to request to remote peer {}", sender);
1304 return;
1305 }
1306
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001307 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001308
1309 // 2-way Anti-Entropy for now
1310 try {
1311 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1312 } catch (IOException e) {
1313 log.error("Failed to send response advertisement to " + sender, e);
1314 }
1315
1316// Sketch of 3-way Anti-Entropy
1317// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1318// ClusterMessage message = new ClusterMessage(
1319// clusterService.getLocalNode().id(),
1320// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1321// SERIALIZER.encode(request));
1322//
1323// try {
1324// clusterCommunicator.unicast(message, advertisement.sender());
1325// } catch (IOException e) {
1326// log.error("Failed to send advertisement reply to "
1327// + advertisement.sender(), e);
1328// }
Madan Jampani47c93732014-10-06 20:46:08 -07001329 }
1330
Madan Jampani255a58b2014-10-09 12:08:20 -07001331 private void notifyDelegateIfNotNull(DeviceEvent event) {
1332 if (event != null) {
1333 notifyDelegate(event);
1334 }
1335 }
1336
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001337 private final class SendAdvertisementTask implements Runnable {
1338
1339 @Override
1340 public void run() {
1341 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001342 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001343 return;
1344 }
1345
1346 try {
1347 final NodeId self = clusterService.getLocalNode().id();
1348 Set<ControllerNode> nodes = clusterService.getNodes();
1349
1350 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1351 .transform(toNodeId())
1352 .toList();
1353
1354 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001355 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001356 return;
1357 }
1358
1359 NodeId peer;
1360 do {
1361 int idx = RandomUtils.nextInt(0, nodeIds.size());
1362 peer = nodeIds.get(idx);
1363 } while (peer.equals(self));
1364
1365 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1366
1367 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001368 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001369 return;
1370 }
1371
1372 try {
1373 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1374 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001375 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001376 return;
1377 }
1378 } catch (Exception e) {
1379 // catch all Exception to avoid Scheduled task being suppressed.
1380 log.error("Exception thrown while sending advertisement", e);
1381 }
1382 }
1383 }
1384
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001385 private final class InternalDeviceEventListener
1386 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001387 @Override
1388 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001389
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001390 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001391 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001392
Madan Jampani47c93732014-10-06 20:46:08 -07001393 ProviderId providerId = event.providerId();
1394 DeviceId deviceId = event.deviceId();
1395 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001396
Madan Jampani2af244a2015-02-22 13:12:01 -08001397 try {
1398 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1399 } catch (Exception e) {
1400 log.warn("Exception thrown handling device update", e);
1401 }
Madan Jampani47c93732014-10-06 20:46:08 -07001402 }
1403 }
1404
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001405 private final class InternalDeviceOfflineEventListener
1406 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001407 @Override
1408 public void handle(ClusterMessage message) {
1409
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001410 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001411 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001412
1413 DeviceId deviceId = event.deviceId();
1414 Timestamp timestamp = event.timestamp();
1415
Madan Jampani2af244a2015-02-22 13:12:01 -08001416 try {
1417 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1418 } catch (Exception e) {
1419 log.warn("Exception thrown handling device offline", e);
1420 }
Madan Jampani25322532014-10-08 11:20:38 -07001421 }
1422 }
1423
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001424 private final class InternalRemoveRequestListener
1425 implements ClusterMessageHandler {
1426 @Override
1427 public void handle(ClusterMessage message) {
1428 log.debug("Received device remove request from peer: {}", message.sender());
1429 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001430
Madan Jampani2af244a2015-02-22 13:12:01 -08001431 try {
1432 removeDevice(did);
1433 } catch (Exception e) {
1434 log.warn("Exception thrown handling device remove", e);
1435 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001436 }
1437 }
1438
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001439 private final class InternalDeviceRemovedEventListener
1440 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001441 @Override
1442 public void handle(ClusterMessage message) {
1443
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001444 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001445 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001446
1447 DeviceId deviceId = event.deviceId();
1448 Timestamp timestamp = event.timestamp();
1449
Madan Jampani2af244a2015-02-22 13:12:01 -08001450 try {
1451 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1452 } catch (Exception e) {
1453 log.warn("Exception thrown handling device removed", e);
1454 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001455 }
1456 }
1457
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001458 private final class InternalPortEventListener
1459 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001460 @Override
1461 public void handle(ClusterMessage message) {
1462
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001463 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001464 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001465
1466 ProviderId providerId = event.providerId();
1467 DeviceId deviceId = event.deviceId();
1468 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1469
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001470 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001471 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001472 // Note: dropped information will be recovered by anti-entropy
1473 return;
1474 }
1475
Madan Jampani2af244a2015-02-22 13:12:01 -08001476 try {
1477 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1478 } catch (Exception e) {
1479 log.warn("Exception thrown handling port update", e);
1480 }
Madan Jampani47c93732014-10-06 20:46:08 -07001481 }
1482 }
1483
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001484 private final class InternalPortStatusEventListener
1485 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001486 @Override
1487 public void handle(ClusterMessage message) {
1488
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001489 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001490 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001491
1492 ProviderId providerId = event.providerId();
1493 DeviceId deviceId = event.deviceId();
1494 Timestamped<PortDescription> portDescription = event.portDescription();
1495
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001496 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001497 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001498 // Note: dropped information will be recovered by anti-entropy
1499 return;
1500 }
1501
Madan Jampani2af244a2015-02-22 13:12:01 -08001502 try {
1503 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1504 } catch (Exception e) {
1505 log.warn("Exception thrown handling port update", e);
1506 }
Madan Jampani47c93732014-10-06 20:46:08 -07001507 }
1508 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001509
1510 private final class InternalDeviceAdvertisementListener
1511 implements ClusterMessageHandler {
1512
1513 @Override
1514 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001515 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001516 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001517 try {
1518 handleAdvertisement(advertisement);
1519 } catch (Exception e) {
1520 log.warn("Exception thrown handling Device advertisements.", e);
1521 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001522 }
1523 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001524
1525 private final class DeviceInjectedEventListener
1526 implements ClusterMessageHandler {
1527 @Override
1528 public void handle(ClusterMessage message) {
1529
1530 log.debug("Received injected device event from peer: {}", message.sender());
1531 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1532
1533 ProviderId providerId = event.providerId();
1534 DeviceId deviceId = event.deviceId();
1535 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001536 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1537 // workaround for ONOS-1208
1538 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1539 return;
1540 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001541
Madan Jampani2af244a2015-02-22 13:12:01 -08001542 try {
1543 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1544 } catch (Exception e) {
1545 log.warn("Exception thrown handling device injected event.", e);
1546 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001547 }
1548 }
1549
1550 private final class PortInjectedEventListener
1551 implements ClusterMessageHandler {
1552 @Override
1553 public void handle(ClusterMessage message) {
1554
1555 log.debug("Received injected port event from peer: {}", message.sender());
1556 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1557
1558 ProviderId providerId = event.providerId();
1559 DeviceId deviceId = event.deviceId();
1560 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001561 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1562 // workaround for ONOS-1208
1563 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1564 return;
1565 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001566
Madan Jampani2af244a2015-02-22 13:12:01 -08001567 try {
1568 updatePorts(providerId, deviceId, portDescriptions);
1569 } catch (Exception e) {
1570 log.warn("Exception thrown handling port injected event.", e);
1571 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001572 }
1573 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001574}