blob: 8852c4918f64f936264cf7adfcc86f15b2337f30 [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);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700862 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800863 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(),
Sho SHIMIZU0abceb82015-05-04 09:20:53 -07001038 ochPortDesc.isTunable(), ochPortDesc.lambda(), annotations);
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001039 case ODUCLT:
1040 OduCltPortDescription oduCltPortDesc = (OduCltPortDescription) portDesc.value();
1041 return new OduCltPort(device, number, isEnabled, oduCltPortDesc.signalType(), annotations);
1042 default:
1043 return new DefaultPort(device, number, isEnabled, portDesc.value().type(),
1044 portDesc.value().portSpeed(), annotations);
1045 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001046 }
1047
1048 /**
1049 * @return primary ProviderID, or randomly chosen one if none exists
1050 */
1051 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001052 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001053 ProviderId fallBackPrimary = null;
1054 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1055 if (!e.getKey().isAncillary()) {
1056 return e.getKey();
1057 } else if (fallBackPrimary == null) {
1058 // pick randomly as a fallback in case there is no primary
1059 fallBackPrimary = e.getKey();
1060 }
1061 }
1062 return fallBackPrimary;
1063 }
1064
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001065 private DeviceDescriptions getPrimaryDescriptions(
1066 Map<ProviderId, DeviceDescriptions> providerDescs) {
1067 ProviderId pid = pickPrimaryPID(providerDescs);
1068 return providerDescs.get(pid);
1069 }
1070
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001071 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001072 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001073 }
1074
Jonathan Hart7d656f42015-01-27 14:07:23 -08001075 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001076 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001077 }
Madan Jampani47c93732014-10-06 20:46:08 -07001078
Jonathan Hart7d656f42015-01-27 14:07:23 -08001079 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001080 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001081 }
1082
Jonathan Hart7d656f42015-01-27 14:07:23 -08001083 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001084 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001085 }
1086
Jonathan Hart7d656f42015-01-27 14:07:23 -08001087 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001088 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001089 }
1090
Jonathan Hart7d656f42015-01-27 14:07:23 -08001091 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001092 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001093 }
1094
Jonathan Hart7d656f42015-01-27 14:07:23 -08001095 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001096 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1097 }
1098
1099 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1100 try {
1101 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1102 } catch (IOException e) {
1103 log.error("Failed to send" + event + " to " + recipient, e);
1104 }
1105 }
1106
1107 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1108 try {
1109 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1110 } catch (IOException e) {
1111 log.error("Failed to send" + event + " to " + recipient, e);
1112 }
1113 }
1114
1115 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1116 try {
1117 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1118 } catch (IOException e) {
1119 log.error("Failed to send" + event + " to " + recipient, e);
1120 }
1121 }
1122
1123 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1124 try {
1125 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1126 } catch (IOException e) {
1127 log.error("Failed to send" + event + " to " + recipient, e);
1128 }
1129 }
1130
1131 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1132 try {
1133 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1134 } catch (IOException e) {
1135 log.error("Failed to send" + event + " to " + recipient, e);
1136 }
1137 }
1138
1139 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1140 final NodeId self = clusterService.getLocalNode().id();
1141
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001142 final int numDevices = deviceDescs.size();
1143 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1144 final int portsPerDevice = 8; // random factor to minimize reallocation
1145 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1146 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001147
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001148 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001149
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001150 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001151 synchronized (devDescs) {
1152
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001153 // send device offline timestamp
1154 Timestamp lOffline = this.offline.get(deviceId);
1155 if (lOffline != null) {
1156 adOffline.put(deviceId, lOffline);
1157 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001158
1159 for (Entry<ProviderId, DeviceDescriptions>
1160 prov : devDescs.entrySet()) {
1161
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001162 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001163 final ProviderId provId = prov.getKey();
1164 final DeviceDescriptions descs = prov.getValue();
1165
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001166 adDevices.put(new DeviceFragmentId(deviceId, provId),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001167 descs.getDeviceDesc().timestamp());
1168
1169 for (Entry<PortNumber, Timestamped<PortDescription>>
1170 portDesc : descs.getPortDescs().entrySet()) {
1171
1172 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001173 adPorts.put(new PortFragmentId(deviceId, provId, number),
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001174 portDesc.getValue().timestamp());
1175 }
1176 }
1177 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001178 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001179
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001180 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001181 }
1182
1183 /**
1184 * Responds to anti-entropy advertisement message.
1185 * <P>
1186 * Notify sender about out-dated information using regular replication message.
1187 * Send back advertisement to sender if not in sync.
1188 *
1189 * @param advertisement to respond to
1190 */
1191 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1192
1193 final NodeId sender = advertisement.sender();
1194
1195 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1196 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1197 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1198
1199 // Fragments to request
1200 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1201 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1202
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001203 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001204 final DeviceId deviceId = de.getKey();
1205 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1206
1207 synchronized (lDevice) {
1208 // latestTimestamp across provider
1209 // Note: can be null initially
1210 Timestamp localLatest = offline.get(deviceId);
1211
1212 // handle device Ads
1213 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1214 final ProviderId provId = prov.getKey();
1215 final DeviceDescriptions lDeviceDescs = prov.getValue();
1216
1217 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1218
1219
1220 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1221 Timestamp advDevTimestamp = devAds.get(devFragId);
1222
Jonathan Hart403ea932015-02-20 16:23:00 -08001223 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1224 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001225 // remote does not have it or outdated, suggest
1226 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1227 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1228 // local is outdated, request
1229 reqDevices.add(devFragId);
1230 }
1231
1232 // handle port Ads
1233 for (Entry<PortNumber, Timestamped<PortDescription>>
1234 pe : lDeviceDescs.getPortDescs().entrySet()) {
1235
1236 final PortNumber num = pe.getKey();
1237 final Timestamped<PortDescription> lPort = pe.getValue();
1238
1239 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1240
1241 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001242 if (advPortTimestamp == null || lPort.isNewerThan(
1243 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001244 // remote does not have it or outdated, suggest
1245 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1246 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1247 // local is outdated, request
1248 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1249 reqPorts.add(portFragId);
1250 }
1251
1252 // remove port Ad already processed
1253 portAds.remove(portFragId);
1254 } // end local port loop
1255
1256 // remove device Ad already processed
1257 devAds.remove(devFragId);
1258
1259 // find latest and update
1260 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1261 if (localLatest == null ||
1262 providerLatest.compareTo(localLatest) > 0) {
1263 localLatest = providerLatest;
1264 }
1265 } // end local provider loop
1266
1267 // checking if remote timestamp is more recent.
1268 Timestamp rOffline = offlineAds.get(deviceId);
1269 if (rOffline != null &&
1270 rOffline.compareTo(localLatest) > 0) {
1271 // remote offline timestamp suggests that the
1272 // device is off-line
1273 markOfflineInternal(deviceId, rOffline);
1274 }
1275
1276 Timestamp lOffline = offline.get(deviceId);
1277 if (lOffline != null && rOffline == null) {
1278 // locally offline, but remote is online, suggest offline
1279 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1280 }
1281
1282 // remove device offline Ad already processed
1283 offlineAds.remove(deviceId);
1284 } // end local device loop
1285 } // device lock
1286
1287 // If there is any Ads left, request them
1288 log.trace("Ads left {}, {}", devAds, portAds);
1289 reqDevices.addAll(devAds.keySet());
1290 reqPorts.addAll(portAds.keySet());
1291
1292 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1293 log.trace("Nothing to request to remote peer {}", sender);
1294 return;
1295 }
1296
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001297 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001298
1299 // 2-way Anti-Entropy for now
1300 try {
1301 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1302 } catch (IOException e) {
1303 log.error("Failed to send response advertisement to " + sender, e);
1304 }
1305
1306// Sketch of 3-way Anti-Entropy
1307// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1308// ClusterMessage message = new ClusterMessage(
1309// clusterService.getLocalNode().id(),
1310// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1311// SERIALIZER.encode(request));
1312//
1313// try {
1314// clusterCommunicator.unicast(message, advertisement.sender());
1315// } catch (IOException e) {
1316// log.error("Failed to send advertisement reply to "
1317// + advertisement.sender(), e);
1318// }
Madan Jampani47c93732014-10-06 20:46:08 -07001319 }
1320
Madan Jampani255a58b2014-10-09 12:08:20 -07001321 private void notifyDelegateIfNotNull(DeviceEvent event) {
1322 if (event != null) {
1323 notifyDelegate(event);
1324 }
1325 }
1326
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001327 private final class SendAdvertisementTask implements Runnable {
1328
1329 @Override
1330 public void run() {
1331 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001332 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001333 return;
1334 }
1335
1336 try {
1337 final NodeId self = clusterService.getLocalNode().id();
1338 Set<ControllerNode> nodes = clusterService.getNodes();
1339
1340 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1341 .transform(toNodeId())
1342 .toList();
1343
1344 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001345 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001346 return;
1347 }
1348
1349 NodeId peer;
1350 do {
1351 int idx = RandomUtils.nextInt(0, nodeIds.size());
1352 peer = nodeIds.get(idx);
1353 } while (peer.equals(self));
1354
1355 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1356
1357 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001358 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001359 return;
1360 }
1361
1362 try {
1363 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1364 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001365 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001366 return;
1367 }
1368 } catch (Exception e) {
1369 // catch all Exception to avoid Scheduled task being suppressed.
1370 log.error("Exception thrown while sending advertisement", e);
1371 }
1372 }
1373 }
1374
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001375 private final class InternalDeviceEventListener
1376 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001377 @Override
1378 public void handle(ClusterMessage message) {
Madan Jampani25322532014-10-08 11:20:38 -07001379
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001380 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001381 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001382
Madan Jampani47c93732014-10-06 20:46:08 -07001383 ProviderId providerId = event.providerId();
1384 DeviceId deviceId = event.deviceId();
1385 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001386
Madan Jampani2af244a2015-02-22 13:12:01 -08001387 try {
1388 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1389 } catch (Exception e) {
1390 log.warn("Exception thrown handling device update", e);
1391 }
Madan Jampani47c93732014-10-06 20:46:08 -07001392 }
1393 }
1394
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001395 private final class InternalDeviceOfflineEventListener
1396 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001397 @Override
1398 public void handle(ClusterMessage message) {
1399
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001400 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001401 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001402
1403 DeviceId deviceId = event.deviceId();
1404 Timestamp timestamp = event.timestamp();
1405
Madan Jampani2af244a2015-02-22 13:12:01 -08001406 try {
1407 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1408 } catch (Exception e) {
1409 log.warn("Exception thrown handling device offline", e);
1410 }
Madan Jampani25322532014-10-08 11:20:38 -07001411 }
1412 }
1413
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001414 private final class InternalRemoveRequestListener
1415 implements ClusterMessageHandler {
1416 @Override
1417 public void handle(ClusterMessage message) {
1418 log.debug("Received device remove request from peer: {}", message.sender());
1419 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001420
Madan Jampani2af244a2015-02-22 13:12:01 -08001421 try {
1422 removeDevice(did);
1423 } catch (Exception e) {
1424 log.warn("Exception thrown handling device remove", e);
1425 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001426 }
1427 }
1428
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001429 private final class InternalDeviceRemovedEventListener
1430 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001431 @Override
1432 public void handle(ClusterMessage message) {
1433
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001434 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001435 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001436
1437 DeviceId deviceId = event.deviceId();
1438 Timestamp timestamp = event.timestamp();
1439
Madan Jampani2af244a2015-02-22 13:12:01 -08001440 try {
1441 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1442 } catch (Exception e) {
1443 log.warn("Exception thrown handling device removed", e);
1444 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001445 }
1446 }
1447
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001448 private final class InternalPortEventListener
1449 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001450 @Override
1451 public void handle(ClusterMessage message) {
1452
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001453 log.debug("Received port update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001454 InternalPortEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001455
1456 ProviderId providerId = event.providerId();
1457 DeviceId deviceId = event.deviceId();
1458 Timestamped<List<PortDescription>> portDescriptions = event.portDescriptions();
1459
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001460 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001461 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001462 // Note: dropped information will be recovered by anti-entropy
1463 return;
1464 }
1465
Madan Jampani2af244a2015-02-22 13:12:01 -08001466 try {
1467 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1468 } catch (Exception e) {
1469 log.warn("Exception thrown handling port update", e);
1470 }
Madan Jampani47c93732014-10-06 20:46:08 -07001471 }
1472 }
1473
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001474 private final class InternalPortStatusEventListener
1475 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001476 @Override
1477 public void handle(ClusterMessage message) {
1478
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001479 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001480 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001481
1482 ProviderId providerId = event.providerId();
1483 DeviceId deviceId = event.deviceId();
1484 Timestamped<PortDescription> portDescription = event.portDescription();
1485
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001486 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001487 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001488 // Note: dropped information will be recovered by anti-entropy
1489 return;
1490 }
1491
Madan Jampani2af244a2015-02-22 13:12:01 -08001492 try {
1493 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1494 } catch (Exception e) {
1495 log.warn("Exception thrown handling port update", e);
1496 }
Madan Jampani47c93732014-10-06 20:46:08 -07001497 }
1498 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001499
1500 private final class InternalDeviceAdvertisementListener
1501 implements ClusterMessageHandler {
1502
1503 @Override
1504 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001505 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001506 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001507 try {
1508 handleAdvertisement(advertisement);
1509 } catch (Exception e) {
1510 log.warn("Exception thrown handling Device advertisements.", e);
1511 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001512 }
1513 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001514
1515 private final class DeviceInjectedEventListener
1516 implements ClusterMessageHandler {
1517 @Override
1518 public void handle(ClusterMessage message) {
1519
1520 log.debug("Received injected device event from peer: {}", message.sender());
1521 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1522
1523 ProviderId providerId = event.providerId();
1524 DeviceId deviceId = event.deviceId();
1525 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001526 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1527 // workaround for ONOS-1208
1528 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1529 return;
1530 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001531
Madan Jampani2af244a2015-02-22 13:12:01 -08001532 try {
1533 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1534 } catch (Exception e) {
1535 log.warn("Exception thrown handling device injected event.", e);
1536 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001537 }
1538 }
1539
1540 private final class PortInjectedEventListener
1541 implements ClusterMessageHandler {
1542 @Override
1543 public void handle(ClusterMessage message) {
1544
1545 log.debug("Received injected port event from peer: {}", message.sender());
1546 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1547
1548 ProviderId providerId = event.providerId();
1549 DeviceId deviceId = event.deviceId();
1550 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001551 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1552 // workaround for ONOS-1208
1553 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1554 return;
1555 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001556
Madan Jampani2af244a2015-02-22 13:12:01 -08001557 try {
1558 updatePorts(providerId, deviceId, portDescriptions);
1559 } catch (Exception e) {
1560 log.warn("Exception thrown handling port injected event.", e);
1561 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001562 }
1563 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001564}