blob: aa736a18ad2d74474d551d8c02138b4db76db054 [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;
72import org.onosproject.store.serializers.impl.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) {
720
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700721 final Timestamp newTimestamp;
722 try {
723 newTimestamp = deviceClockService.getTimestamp(deviceId);
724 } catch (IllegalStateException e) {
725 log.info("Timestamp was not available for device {}", deviceId);
726 log.debug(" discarding {}", portDescription);
727 // Failed to generate timestamp. Ignoring.
728 // See updatePorts comment
729 return null;
730 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700731 final Timestamped<PortDescription> deltaDesc
732 = new Timestamped<>(portDescription, newTimestamp);
733 final DeviceEvent event;
734 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800735 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
736 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700737 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800738 mergedDesc = device.get(providerId)
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700739 .getPortDesc(portDescription.portNumber());
740 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700741 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700742 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
743 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800744 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700745 }
746 return event;
747 }
748
749 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
750 Timestamped<PortDescription> deltaDesc) {
751
752 Device device = devices.get(deviceId);
753 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
754
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700755 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700756 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
757
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700758 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700759
760 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
761 log.debug("Ignoring outdated event: {}", deltaDesc);
762 return null;
763 }
764
765 DeviceDescriptions descs = descsMap.get(providerId);
766 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700767 verify(descs != null,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700768 "Device description for Device ID %s from Provider %s was not found",
769 deviceId, providerId);
770
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700771 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
772 final PortNumber number = deltaDesc.value().portNumber();
773 final Port oldPort = ports.get(number);
774 final Port newPort;
775
776 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
777 if (existingPortDesc == null ||
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700778 deltaDesc.isNewer(existingPortDesc)) {
779 // on new port or valid update
780 // update description
781 descs.putPortDesc(deltaDesc);
782 newPort = composePort(device, number, descsMap);
783 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700784 // same or outdated event, ignored.
785 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700786 return null;
787 }
788
789 if (oldPort == null) {
790 return createPort(device, newPort, ports);
791 } else {
792 return updatePort(device, oldPort, newPort, ports);
793 }
794 }
795 }
796
797 @Override
798 public List<Port> getPorts(DeviceId deviceId) {
799 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
800 if (ports == null) {
801 return Collections.emptyList();
802 }
803 return ImmutableList.copyOf(ports.values());
804 }
805
806 @Override
sangho538108b2015-04-08 14:29:20 -0700807 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
808 Collection<PortStatistics> portStats) {
809
810 ConcurrentMap<PortNumber, PortStatistics> statsMap = devicePortStats.get(deviceId);
811 if (statsMap == null) {
812 statsMap = Maps.newConcurrentMap();
813 devicePortStats.put(deviceId, statsMap);
814 }
815
816 for (PortStatistics stat: portStats) {
817 PortNumber portNumber = PortNumber.portNumber(stat.port());
818 statsMap.put(portNumber, stat);
819 }
820
821 return new DeviceEvent(PORT_STATS_UPDATED, devices.get(deviceId), null);
822 }
823
824 @Override
825 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
826
827 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
828 if (portStats == null) {
829 return Collections.emptyList();
830 }
831 return ImmutableList.copyOf(portStats.values());
832 }
833
834 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700835 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
836 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
837 return ports == null ? null : ports.get(portNumber);
838 }
839
840 @Override
841 public boolean isAvailable(DeviceId deviceId) {
842 return availableDevices.contains(deviceId);
843 }
844
845 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700846 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800847 final NodeId myId = clusterService.getLocalNode().id();
848 NodeId master = mastershipService.getMasterFor(deviceId);
849
850 // if there exist a master, forward
851 // if there is no master, try to become one and process
852
853 boolean relinquishAtEnd = false;
854 if (master == null) {
855 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
856 if (myRole != MastershipRole.NONE) {
857 relinquishAtEnd = true;
858 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800859 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800860 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800861 MastershipTerm term = termService.getMastershipTerm(deviceId);
862 if (myId.equals(term.master())) {
863 master = myId;
864 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700865 }
866
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800867 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800868 log.debug("{} has control of {}, forwarding remove request",
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800869 master, deviceId);
870
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800871 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700872 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800873 /* error log:
874 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
875 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800876
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800877 // event will be triggered after master processes it.
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800878 return null;
879 }
880
881 // I have control..
882
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700883 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700884 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700885 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800886 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700887 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800888 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700889 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800890 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800891 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800892 mastershipService.relinquishMastership(deviceId);
893 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700894 return event;
895 }
896
897 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
898 Timestamp timestamp) {
899
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700900 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700901 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700902 // accept removal request if given timestamp is newer than
903 // the latest Timestamp from Primary provider
904 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
905 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
906 if (timestamp.compareTo(lastTimestamp) <= 0) {
907 // outdated event ignore
908 return null;
909 }
910 removalRequest.put(deviceId, timestamp);
911
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700912 Device device = devices.remove(deviceId);
913 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700914 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
915 if (ports != null) {
916 ports.clear();
917 }
918 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700919 descs.clear();
920 return device == null ? null :
921 new DeviceEvent(DEVICE_REMOVED, device, null);
922 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700923 }
924
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700925 /**
926 * Checks if given timestamp is superseded by removal request
927 * with more recent timestamp.
928 *
929 * @param deviceId identifier of a device
930 * @param timestampToCheck timestamp of an event to check
931 * @return true if device is already removed
932 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700933 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
934 Timestamp removalTimestamp = removalRequest.get(deviceId);
935 if (removalTimestamp != null &&
936 removalTimestamp.compareTo(timestampToCheck) >= 0) {
937 // removalRequest is more recent
938 return true;
939 }
940 return false;
941 }
942
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700943 /**
944 * Returns a Device, merging description given from multiple Providers.
945 *
946 * @param deviceId device identifier
947 * @param providerDescs Collection of Descriptions from multiple providers
948 * @return Device instance
949 */
950 private Device composeDevice(DeviceId deviceId,
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700951 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700952
Thomas Vachuska444eda62014-10-28 13:09:42 -0700953 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700954
955 ProviderId primary = pickPrimaryPID(providerDescs);
956
957 DeviceDescriptions desc = providerDescs.get(primary);
958
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700959 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700960 Type type = base.type();
961 String manufacturer = base.manufacturer();
962 String hwVersion = base.hwVersion();
963 String swVersion = base.swVersion();
964 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700965 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700966 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
967 annotations = merge(annotations, base.annotations());
968
969 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
970 if (e.getKey().equals(primary)) {
971 continue;
972 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800973 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700974 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700975 // Currently assuming there will never be a key conflict between
976 // providers
977
978 // annotation merging. not so efficient, should revisit later
979 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
980 }
981
982 return new DefaultDevice(primary, deviceId , type, manufacturer,
alshabib7911a052014-10-16 17:49:37 -0700983 hwVersion, swVersion, serialNumber,
984 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700985 }
986
987 /**
988 * Returns a Port, merging description given from multiple Providers.
989 *
990 * @param device device the port is on
991 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700992 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700993 * @return Port instance
994 */
995 private Port composePort(Device device, PortNumber number,
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700996 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700997
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700998 ProviderId primary = pickPrimaryPID(descsMap);
999 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001000 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001001 boolean isEnabled = false;
1002 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
1003
1004 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1005 if (portDesc != null) {
1006 isEnabled = portDesc.value().isEnabled();
1007 annotations = merge(annotations, portDesc.value().annotations());
1008 }
1009
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) {
1022 annotations = merge(annotations, otherPortDesc.value().annotations());
1023 }
1024 }
1025
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001026 if (portDesc == null) {
1027 return new DefaultPort(device, number, false, annotations);
1028 }
1029
1030 switch (portDesc.value().type()) {
1031 case OMS:
1032 OmsPortDescription omsPortDesc = (OmsPortDescription) portDesc.value();
1033 return new OmsPort(device, number, isEnabled, omsPortDesc.minFrequency(),
1034 omsPortDesc.maxFrequency(), omsPortDesc.grid());
1035 case OCH:
1036 OchPortDescription ochPortDesc = (OchPortDescription) portDesc.value();
1037 return new OchPort(device, number, isEnabled, ochPortDesc.signalType(),
1038 ochPortDesc.isTunable(), ochPortDesc.gridType(), ochPortDesc.channelSpacing(),
1039 ochPortDesc.spacingMultiplier(), ochPortDesc.slotGranularity(), annotations);
1040 case ODUCLT:
1041 OduCltPortDescription oduCltPortDesc = (OduCltPortDescription) portDesc.value();
1042 return new OduCltPort(device, number, isEnabled, oduCltPortDesc.signalType(), annotations);
1043 default:
1044 return new DefaultPort(device, number, isEnabled, portDesc.value().type(),
1045 portDesc.value().portSpeed(), annotations);
1046 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001047 }
1048
1049 /**
1050 * @return primary ProviderID, or randomly chosen one if none exists
1051 */
1052 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001053 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001054 ProviderId fallBackPrimary = null;
1055 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1056 if (!e.getKey().isAncillary()) {
1057 return e.getKey();
1058 } else if (fallBackPrimary == null) {
1059 // pick randomly as a fallback in case there is no primary
1060 fallBackPrimary = e.getKey();
1061 }
1062 }
1063 return fallBackPrimary;
1064 }
1065
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001066 private DeviceDescriptions getPrimaryDescriptions(
1067 Map<ProviderId, DeviceDescriptions> providerDescs) {
1068 ProviderId pid = pickPrimaryPID(providerDescs);
1069 return providerDescs.get(pid);
1070 }
1071
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001072 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001073 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001074 }
1075
Jonathan Hart7d656f42015-01-27 14:07:23 -08001076 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001077 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001078 }
Madan Jampani47c93732014-10-06 20:46:08 -07001079
Jonathan Hart7d656f42015-01-27 14:07:23 -08001080 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001081 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001082 }
1083
Jonathan Hart7d656f42015-01-27 14:07:23 -08001084 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001085 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001086 }
1087
Jonathan Hart7d656f42015-01-27 14:07:23 -08001088 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001089 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001090 }
1091
Jonathan Hart7d656f42015-01-27 14:07:23 -08001092 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001093 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001094 }
1095
Jonathan Hart7d656f42015-01-27 14:07:23 -08001096 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001097 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1098 }
1099
1100 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1101 try {
1102 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1103 } catch (IOException e) {
1104 log.error("Failed to send" + event + " to " + recipient, e);
1105 }
1106 }
1107
1108 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1109 try {
1110 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1111 } catch (IOException e) {
1112 log.error("Failed to send" + event + " to " + recipient, e);
1113 }
1114 }
1115
1116 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1117 try {
1118 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1119 } catch (IOException e) {
1120 log.error("Failed to send" + event + " to " + recipient, e);
1121 }
1122 }
1123
1124 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1125 try {
1126 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1127 } catch (IOException e) {
1128 log.error("Failed to send" + event + " to " + recipient, e);
1129 }
1130 }
1131
1132 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1133 try {
1134 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1135 } catch (IOException e) {
1136 log.error("Failed to send" + event + " to " + recipient, e);
1137 }
1138 }
1139
1140 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1141 final NodeId self = clusterService.getLocalNode().id();
1142
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001143 final int numDevices = deviceDescs.size();
1144 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1145 final int portsPerDevice = 8; // random factor to minimize reallocation
1146 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1147 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001148
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001149 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001150
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001151 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001152 synchronized (devDescs) {
1153
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001154 // send device offline timestamp
1155 Timestamp lOffline = this.offline.get(deviceId);
1156 if (lOffline != null) {
1157 adOffline.put(deviceId, lOffline);
1158 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001159
1160 for (Entry<ProviderId, DeviceDescriptions>
1161 prov : devDescs.entrySet()) {
1162
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001163 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001164 final ProviderId provId = prov.getKey();
1165 final DeviceDescriptions descs = prov.getValue();
1166
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001167 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001168 descs.getDeviceDesc().timestamp());
1169
1170 for (Entry<PortNumber, Timestamped<PortDescription>>
1171 portDesc : descs.getPortDescs().entrySet()) {
1172
1173 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001174 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001175 portDesc.getValue().timestamp());
1176 }
1177 }
1178 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001179 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001180
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001181 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001182 }
1183
1184 /**
1185 * Responds to anti-entropy advertisement message.
1186 * <P>
1187 * Notify sender about out-dated information using regular replication message.
1188 * Send back advertisement to sender if not in sync.
1189 *
1190 * @param advertisement to respond to
1191 */
1192 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1193
1194 final NodeId sender = advertisement.sender();
1195
1196 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1197 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1198 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1199
1200 // Fragments to request
1201 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1202 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1203
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001204 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001205 final DeviceId deviceId = de.getKey();
1206 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1207
1208 synchronized (lDevice) {
1209 // latestTimestamp across provider
1210 // Note: can be null initially
1211 Timestamp localLatest = offline.get(deviceId);
1212
1213 // handle device Ads
1214 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1215 final ProviderId provId = prov.getKey();
1216 final DeviceDescriptions lDeviceDescs = prov.getValue();
1217
1218 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1219
1220
1221 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1222 Timestamp advDevTimestamp = devAds.get(devFragId);
1223
Jonathan Hart403ea932015-02-20 16:23:00 -08001224 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1225 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001226 // remote does not have it or outdated, suggest
1227 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1228 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1229 // local is outdated, request
1230 reqDevices.add(devFragId);
1231 }
1232
1233 // handle port Ads
1234 for (Entry<PortNumber, Timestamped<PortDescription>>
1235 pe : lDeviceDescs.getPortDescs().entrySet()) {
1236
1237 final PortNumber num = pe.getKey();
1238 final Timestamped<PortDescription> lPort = pe.getValue();
1239
1240 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1241
1242 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001243 if (advPortTimestamp == null || lPort.isNewerThan(
1244 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001245 // remote does not have it or outdated, suggest
1246 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1247 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1248 // local is outdated, request
1249 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1250 reqPorts.add(portFragId);
1251 }
1252
1253 // remove port Ad already processed
1254 portAds.remove(portFragId);
1255 } // end local port loop
1256
1257 // remove device Ad already processed
1258 devAds.remove(devFragId);
1259
1260 // find latest and update
1261 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1262 if (localLatest == null ||
1263 providerLatest.compareTo(localLatest) > 0) {
1264 localLatest = providerLatest;
1265 }
1266 } // end local provider loop
1267
1268 // checking if remote timestamp is more recent.
1269 Timestamp rOffline = offlineAds.get(deviceId);
1270 if (rOffline != null &&
1271 rOffline.compareTo(localLatest) > 0) {
1272 // remote offline timestamp suggests that the
1273 // device is off-line
1274 markOfflineInternal(deviceId, rOffline);
1275 }
1276
1277 Timestamp lOffline = offline.get(deviceId);
1278 if (lOffline != null && rOffline == null) {
1279 // locally offline, but remote is online, suggest offline
1280 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1281 }
1282
1283 // remove device offline Ad already processed
1284 offlineAds.remove(deviceId);
1285 } // end local device loop
1286 } // device lock
1287
1288 // If there is any Ads left, request them
1289 log.trace("Ads left {}, {}", devAds, portAds);
1290 reqDevices.addAll(devAds.keySet());
1291 reqPorts.addAll(portAds.keySet());
1292
1293 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1294 log.trace("Nothing to request to remote peer {}", sender);
1295 return;
1296 }
1297
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001298 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001299
1300 // 2-way Anti-Entropy for now
1301 try {
1302 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1303 } catch (IOException e) {
1304 log.error("Failed to send response advertisement to " + sender, e);
1305 }
1306
1307// Sketch of 3-way Anti-Entropy
1308// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1309// ClusterMessage message = new ClusterMessage(
1310// clusterService.getLocalNode().id(),
1311// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1312// SERIALIZER.encode(request));
1313//
1314// try {
1315// clusterCommunicator.unicast(message, advertisement.sender());
1316// } catch (IOException e) {
1317// log.error("Failed to send advertisement reply to "
1318// + advertisement.sender(), e);
1319// }
Madan Jampani47c93732014-10-06 20:46:08 -07001320 }
1321
Madan Jampani255a58b2014-10-09 12:08:20 -07001322 private void notifyDelegateIfNotNull(DeviceEvent event) {
1323 if (event != null) {
1324 notifyDelegate(event);
1325 }
1326 }
1327
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001328 private final class SendAdvertisementTask implements Runnable {
1329
1330 @Override
1331 public void run() {
1332 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001333 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001334 return;
1335 }
1336
1337 try {
1338 final NodeId self = clusterService.getLocalNode().id();
1339 Set<ControllerNode> nodes = clusterService.getNodes();
1340
1341 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1342 .transform(toNodeId())
1343 .toList();
1344
1345 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001346 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001347 return;
1348 }
1349
1350 NodeId peer;
1351 do {
1352 int idx = RandomUtils.nextInt(0, nodeIds.size());
1353 peer = nodeIds.get(idx);
1354 } while (peer.equals(self));
1355
1356 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1357
1358 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001359 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001360 return;
1361 }
1362
1363 try {
1364 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1365 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001366 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001367 return;
1368 }
1369 } catch (Exception e) {
1370 // catch all Exception to avoid Scheduled task being suppressed.
1371 log.error("Exception thrown while sending advertisement", e);
1372 }
1373 }
1374 }
1375
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001376 private final class InternalDeviceEventListener
1377 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001378 @Override
1379 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001380
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001381 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001382 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001383
Madan Jampani47c93732014-10-06 20:46:08 -07001384 ProviderId providerId = event.providerId();
1385 DeviceId deviceId = event.deviceId();
1386 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001387
Madan Jampani2af244a2015-02-22 13:12:01 -08001388 try {
1389 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1390 } catch (Exception e) {
1391 log.warn("Exception thrown handling device update", e);
1392 }
Madan Jampani47c93732014-10-06 20:46:08 -07001393 }
1394 }
1395
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001396 private final class InternalDeviceOfflineEventListener
1397 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001398 @Override
1399 public void handle(ClusterMessage message) {
1400
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001401 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001402 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001403
1404 DeviceId deviceId = event.deviceId();
1405 Timestamp timestamp = event.timestamp();
1406
Madan Jampani2af244a2015-02-22 13:12:01 -08001407 try {
1408 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1409 } catch (Exception e) {
1410 log.warn("Exception thrown handling device offline", e);
1411 }
Madan Jampani25322532014-10-08 11:20:38 -07001412 }
1413 }
1414
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001415 private final class InternalRemoveRequestListener
1416 implements ClusterMessageHandler {
1417 @Override
1418 public void handle(ClusterMessage message) {
1419 log.debug("Received device remove request from peer: {}", message.sender());
1420 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001421
Madan Jampani2af244a2015-02-22 13:12:01 -08001422 try {
1423 removeDevice(did);
1424 } catch (Exception e) {
1425 log.warn("Exception thrown handling device remove", e);
1426 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001427 }
1428 }
1429
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001430 private final class InternalDeviceRemovedEventListener
1431 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001432 @Override
1433 public void handle(ClusterMessage message) {
1434
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001435 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001436 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001437
1438 DeviceId deviceId = event.deviceId();
1439 Timestamp timestamp = event.timestamp();
1440
Madan Jampani2af244a2015-02-22 13:12:01 -08001441 try {
1442 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1443 } catch (Exception e) {
1444 log.warn("Exception thrown handling device removed", e);
1445 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001446 }
1447 }
1448
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001449 private final class InternalPortEventListener
1450 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001451 @Override
1452 public void handle(ClusterMessage message) {
1453
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001454 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001455 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001456
1457 ProviderId providerId = event.providerId();
1458 DeviceId deviceId = event.deviceId();
1459 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1460
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001461 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001462 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001463 // Note: dropped information will be recovered by anti-entropy
1464 return;
1465 }
1466
Madan Jampani2af244a2015-02-22 13:12:01 -08001467 try {
1468 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1469 } catch (Exception e) {
1470 log.warn("Exception thrown handling port update", e);
1471 }
Madan Jampani47c93732014-10-06 20:46:08 -07001472 }
1473 }
1474
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001475 private final class InternalPortStatusEventListener
1476 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001477 @Override
1478 public void handle(ClusterMessage message) {
1479
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001480 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001481 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001482
1483 ProviderId providerId = event.providerId();
1484 DeviceId deviceId = event.deviceId();
1485 Timestamped<PortDescription> portDescription = event.portDescription();
1486
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001487 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001488 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001489 // Note: dropped information will be recovered by anti-entropy
1490 return;
1491 }
1492
Madan Jampani2af244a2015-02-22 13:12:01 -08001493 try {
1494 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1495 } catch (Exception e) {
1496 log.warn("Exception thrown handling port update", e);
1497 }
Madan Jampani47c93732014-10-06 20:46:08 -07001498 }
1499 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001500
1501 private final class InternalDeviceAdvertisementListener
1502 implements ClusterMessageHandler {
1503
1504 @Override
1505 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001506 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001507 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001508 try {
1509 handleAdvertisement(advertisement);
1510 } catch (Exception e) {
1511 log.warn("Exception thrown handling Device advertisements.", e);
1512 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001513 }
1514 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001515
1516 private final class DeviceInjectedEventListener
1517 implements ClusterMessageHandler {
1518 @Override
1519 public void handle(ClusterMessage message) {
1520
1521 log.debug("Received injected device event from peer: {}", message.sender());
1522 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1523
1524 ProviderId providerId = event.providerId();
1525 DeviceId deviceId = event.deviceId();
1526 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001527 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1528 // workaround for ONOS-1208
1529 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1530 return;
1531 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001532
Madan Jampani2af244a2015-02-22 13:12:01 -08001533 try {
1534 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1535 } catch (Exception e) {
1536 log.warn("Exception thrown handling device injected event.", e);
1537 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001538 }
1539 }
1540
1541 private final class PortInjectedEventListener
1542 implements ClusterMessageHandler {
1543 @Override
1544 public void handle(ClusterMessage message) {
1545
1546 log.debug("Received injected port event from peer: {}", message.sender());
1547 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1548
1549 ProviderId providerId = event.providerId();
1550 DeviceId deviceId = event.deviceId();
1551 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001552 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1553 // workaround for ONOS-1208
1554 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1555 return;
1556 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001557
Madan Jampani2af244a2015-02-22 13:12:01 -08001558 try {
1559 updatePorts(providerId, deviceId, portDescriptions);
1560 } catch (Exception e) {
1561 log.warn("Exception thrown handling port injected event.", e);
1562 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001563 }
1564 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001565}