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