blob: e705567a504192fb0070aa8e5defc1bd672a13d0 [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;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070053import org.onosproject.net.device.DefaultPortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080054import org.onosproject.net.device.DeviceClockService;
55import org.onosproject.net.device.DeviceDescription;
56import org.onosproject.net.device.DeviceEvent;
57import org.onosproject.net.device.DeviceStore;
58import org.onosproject.net.device.DeviceStoreDelegate;
Marc De Leenheer4b18a232015-04-30 11:58:20 -070059import org.onosproject.net.device.OchPortDescription;
60import org.onosproject.net.device.OduCltPortDescription;
61import org.onosproject.net.device.OmsPortDescription;
Brian O'Connorabafb502014-12-02 22:26:20 -080062import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070063import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080064import org.onosproject.net.provider.ProviderId;
65import org.onosproject.store.AbstractStore;
66import org.onosproject.store.Timestamp;
67import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
68import org.onosproject.store.cluster.messaging.ClusterMessage;
69import org.onosproject.store.cluster.messaging.ClusterMessageHandler;
70import org.onosproject.store.cluster.messaging.MessageSubject;
71import org.onosproject.store.impl.Timestamped;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070072import org.onosproject.store.serializers.KryoNamespaces;
Brian O'Connorabafb502014-12-02 22:26:20 -080073import org.onosproject.store.serializers.KryoSerializer;
Brian O'Connor6de2e202015-05-21 14:30:41 -070074import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -070075import org.onosproject.store.service.EventuallyConsistentMap;
76import org.onosproject.store.service.EventuallyConsistentMapEvent;
77import org.onosproject.store.service.EventuallyConsistentMapListener;
78import org.onosproject.store.service.MultiValuedTimestamp;
79import org.onosproject.store.service.StorageService;
80import org.onosproject.store.service.WallClockTimestamp;
81import org.onosproject.store.service.WallclockClockManager;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070082import org.slf4j.Logger;
83
Madan Jampani47c93732014-10-06 20:46:08 -070084import java.io.IOException;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070085import java.util.ArrayList;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070086import java.util.Collection;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070087import java.util.Collections;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070088import java.util.HashMap;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070089import java.util.HashSet;
90import java.util.Iterator;
91import java.util.List;
92import java.util.Map;
93import java.util.Map.Entry;
94import java.util.Objects;
95import java.util.Set;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -070096import java.util.concurrent.ConcurrentMap;
Yuta HIGUCHI80d56592014-11-25 15:11:13 -080097import java.util.concurrent.ExecutorService;
98import java.util.concurrent.Executors;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -070099import java.util.concurrent.ScheduledExecutorService;
100import java.util.concurrent.TimeUnit;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700101
102import static com.google.common.base.Preconditions.checkArgument;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700103import static com.google.common.base.Predicates.notNull;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700104import static com.google.common.base.Verify.verify;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800105import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
106import static org.apache.commons.lang3.concurrent.ConcurrentUtils.createIfAbsentUnchecked;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800107import static org.onlab.util.Tools.groupedThreads;
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800108import static org.onlab.util.Tools.minPriority;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800109import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId;
110import static org.onosproject.net.DefaultAnnotations.merge;
111import static org.onosproject.net.device.DeviceEvent.Type.*;
112import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
113import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.*;
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700114import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800115import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700116
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700117/**
118 * Manages inventory of infrastructure devices using gossip protocol to distribute
119 * information.
120 */
121@Component(immediate = true)
122@Service
123public class GossipDeviceStore
124 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
125 implements DeviceStore {
126
127 private final Logger log = getLogger(getClass());
128
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700129 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800130 // Timeout in milliseconds to process device or ports on remote master node
131 private static final int REMOTE_MASTER_TIMEOUT = 1000;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700132
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700133 // innerMap is used to lock a Device, thus instance should never be replaced.
134 // collection of Description given from various providers
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700135 private final ConcurrentMap<DeviceId, Map<ProviderId, DeviceDescriptions>>
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700136 deviceDescs = Maps.newConcurrentMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700137
138 // cache of Device and Ports generated by compositing descriptions from providers
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700139 private final ConcurrentMap<DeviceId, Device> devices = Maps.newConcurrentMap();
140 private final ConcurrentMap<DeviceId, ConcurrentMap<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700141
142 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
143 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>>
144 portStatsListener = new InternalPortStatsListener();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700145
146 // to be updated under Device lock
147 private final Map<DeviceId, Timestamp> offline = Maps.newHashMap();
148 private final Map<DeviceId, Timestamp> removalRequest = Maps.newHashMap();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700149
150 // available(=UP) devices
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700151 private final Set<DeviceId> availableDevices = Sets.newConcurrentHashSet();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700152
153 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700154 protected DeviceClockService deviceClockService;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700155
Madan Jampani47c93732014-10-06 20:46:08 -0700156 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700157 protected StorageService storageService;
158
159 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampani47c93732014-10-06 20:46:08 -0700160 protected ClusterCommunicationService clusterCommunicator;
161
Madan Jampani53e44e62014-10-07 12:39:51 -0700162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
163 protected ClusterService clusterService;
164
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
166 protected MastershipService mastershipService;
167
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800168 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
169 protected MastershipTermService termService;
170
171
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700172 protected static final KryoSerializer SERIALIZER = new KryoSerializer() {
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700173 @Override
Madan Jampani53e44e62014-10-07 12:39:51 -0700174 protected void setupKryoPool() {
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -0700175 serializerPool = KryoNamespace.newBuilder()
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800176 .register(DistributedStoreSerializers.STORE_COMMON)
177 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
178 .register(new InternalDeviceEventSerializer(), InternalDeviceEvent.class)
179 .register(new InternalDeviceOfflineEventSerializer(), InternalDeviceOfflineEvent.class)
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700180 .register(InternalDeviceRemovedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800181 .register(new InternalPortEventSerializer(), InternalPortEvent.class)
182 .register(new InternalPortStatusEventSerializer(), InternalPortStatusEvent.class)
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700183 .register(DeviceAntiEntropyAdvertisement.class)
184 .register(DeviceFragmentId.class)
185 .register(PortFragmentId.class)
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800186 .register(DeviceInjectedEvent.class)
187 .register(PortInjectedEvent.class)
Yuta HIGUCHI91768e32014-11-22 05:06:35 -0800188 .build();
Madan Jampani53e44e62014-10-07 12:39:51 -0700189 }
Madan Jampani53e44e62014-10-07 12:39:51 -0700190 };
191
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800192 private ExecutorService executor;
193
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800194 private ScheduledExecutorService backgroundExecutor;
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700195
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800196 // TODO make these anti-entropy parameters configurable
197 private long initialDelaySec = 5;
198 private long periodSec = 5;
199
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700200 @Activate
201 public void activate() {
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800202 executor = Executors.newCachedThreadPool(groupedThreads("onos/device", "fg-%d"));
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800203
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800204 backgroundExecutor =
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800205 newSingleThreadScheduledExecutor(minPriority(groupedThreads("onos/device", "bg-%d")));
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700206
Madan Jampani2af244a2015-02-22 13:12:01 -0800207 clusterCommunicator.addSubscriber(
208 GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, new InternalDeviceEventListener(), executor);
209 clusterCommunicator.addSubscriber(
210 GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE,
211 new InternalDeviceOfflineEventListener(),
212 executor);
213 clusterCommunicator.addSubscriber(DEVICE_REMOVE_REQ,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700214 new InternalRemoveRequestListener(),
215 executor);
Madan Jampani2af244a2015-02-22 13:12:01 -0800216 clusterCommunicator.addSubscriber(
217 GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, new InternalDeviceRemovedEventListener(), executor);
218 clusterCommunicator.addSubscriber(
219 GossipDeviceStoreMessageSubjects.PORT_UPDATE, new InternalPortEventListener(), executor);
220 clusterCommunicator.addSubscriber(
221 GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, new InternalPortStatusEventListener(), executor);
222 clusterCommunicator.addSubscriber(
223 GossipDeviceStoreMessageSubjects.DEVICE_ADVERTISE,
224 new InternalDeviceAdvertisementListener(),
225 backgroundExecutor);
226 clusterCommunicator.addSubscriber(
227 GossipDeviceStoreMessageSubjects.DEVICE_INJECTED, new DeviceInjectedEventListener(), executor);
228 clusterCommunicator.addSubscriber(
229 GossipDeviceStoreMessageSubjects.PORT_INJECTED, new PortInjectedEventListener(), executor);
230
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700231 // start anti-entropy thread
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800232 backgroundExecutor.scheduleAtFixedRate(new SendAdvertisementTask(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700233 initialDelaySec, periodSec, TimeUnit.SECONDS);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700234
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700235 // Create a distributed map for port stats.
236 KryoNamespace.Builder deviceDataSerializer = KryoNamespace.newBuilder()
237 .register(KryoNamespaces.API)
238 .register(DefaultPortStatistics.class)
239 .register(DeviceId.class)
240 .register(MultiValuedTimestamp.class)
241 .register(WallClockTimestamp.class);
242
243 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
244 .withName("port-stats")
245 .withSerializer(deviceDataSerializer)
246 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
247 .withClockService(new WallclockClockManager<>())
248 .withTombstonesDisabled()
249 .build();
250 devicePortStats.addListener(portStatsListener);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700251 log.info("Started");
252 }
253
254 @Deactivate
255 public void deactivate() {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700256
Yuta HIGUCHI80d56592014-11-25 15:11:13 -0800257 executor.shutdownNow();
258
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800259 backgroundExecutor.shutdownNow();
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700260 try {
Yuta HIGUCHIc5783592014-12-05 11:13:29 -0800261 if (!backgroundExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700262 log.error("Timeout during executor shutdown");
263 }
264 } catch (InterruptedException e) {
265 log.error("Error during executor shutdown", e);
266 }
267
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700268 deviceDescs.clear();
269 devices.clear();
270 devicePorts.clear();
271 availableDevices.clear();
272 log.info("Stopped");
273 }
274
275 @Override
276 public int getDeviceCount() {
277 return devices.size();
278 }
279
280 @Override
281 public Iterable<Device> getDevices() {
282 return Collections.unmodifiableCollection(devices.values());
283 }
284
285 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800286 public Iterable<Device> getAvailableDevices() {
287 return FluentIterable.from(getDevices())
288 .filter(new Predicate<Device>() {
289
290 @Override
291 public boolean apply(Device input) {
292 return isAvailable(input.id());
293 }
294 });
295 }
296
297 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700298 public Device getDevice(DeviceId deviceId) {
299 return devices.get(deviceId);
300 }
301
302 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700303 public synchronized DeviceEvent createOrUpdateDevice(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700304 DeviceId deviceId,
305 DeviceDescription deviceDescription) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800306 NodeId localNode = clusterService.getLocalNode().id();
307 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
308
309 // Process device update only if we're the master,
310 // otherwise signal the actual master.
311 DeviceEvent deviceEvent = null;
312 if (localNode.equals(deviceNode)) {
313
314 final Timestamp newTimestamp = deviceClockService.getTimestamp(deviceId);
315 final Timestamped<DeviceDescription> deltaDesc = new Timestamped<>(deviceDescription, newTimestamp);
316 final Timestamped<DeviceDescription> mergedDesc;
317 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
318
319 synchronized (device) {
320 deviceEvent = createOrUpdateDeviceInternal(providerId, deviceId, deltaDesc);
321 mergedDesc = device.get(providerId).getDeviceDesc();
322 }
323
324 if (deviceEvent != null) {
325 log.info("Notifying peers of a device update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700326 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800327 notifyPeers(new InternalDeviceEvent(providerId, deviceId, mergedDesc));
328 }
329
330 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800331 // FIXME Temporary hack for NPE (ONOS-1171).
332 // Proper fix is to implement forwarding to master on ConfigProvider
333 // redo ONOS-490
334 if (deviceNode == null) {
335 // silently ignore
336 return null;
337 }
338
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800339
340 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(
341 providerId, deviceId, deviceDescription);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800342
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800343 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700344 clusterCommunicator.unicast(deviceInjectedEvent, DEVICE_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800345 /* error log:
346 log.warn("Failed to process injected device id: {} desc: {} " +
347 "(cluster messaging failed: {})",
348 deviceId, deviceDescription, e);
349 */
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700350 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800351
352 return deviceEvent;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700353 }
354
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700355 private DeviceEvent createOrUpdateDeviceInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700356 DeviceId deviceId,
357 Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700358
359 // Collection of DeviceDescriptions for a Device
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800360 Map<ProviderId, DeviceDescriptions> device
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700361 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700362
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800363 synchronized (device) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700364 // locking per device
365
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700366 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
367 log.debug("Ignoring outdated event: {}", deltaDesc);
368 return null;
369 }
370
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800371 DeviceDescriptions descs = getOrCreateProviderDeviceDescriptions(device, providerId, deltaDesc);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700372
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700373 final Device oldDevice = devices.get(deviceId);
374 final Device newDevice;
375
376 if (deltaDesc == descs.getDeviceDesc() ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700377 deltaDesc.isNewer(descs.getDeviceDesc())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700378 // on new device or valid update
379 descs.putDeviceDesc(deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800380 newDevice = composeDevice(deviceId, device);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700381 } else {
382 // outdated event, ignored.
383 return null;
384 }
385 if (oldDevice == null) {
386 // ADD
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700387 return createDevice(providerId, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700388 } else {
389 // UPDATE or ignore (no change or stale)
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700390 return updateDevice(providerId, oldDevice, newDevice, deltaDesc.timestamp());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700391 }
392 }
393 }
394
395 // Creates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700396 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700397 private DeviceEvent createDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700398 Device newDevice, Timestamp timestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700399
400 // update composed device cache
401 Device oldDevice = devices.putIfAbsent(newDevice.id(), newDevice);
402 verify(oldDevice == null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700403 "Unexpected Device in cache. PID:%s [old=%s, new=%s]",
404 providerId, oldDevice, newDevice);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700405
406 if (!providerId.isAncillary()) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700407 markOnline(newDevice.id(), timestamp);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700408 }
409
410 return new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, newDevice, null);
411 }
412
413 // Updates the device and returns the appropriate event if necessary.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700414 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700415 private DeviceEvent updateDevice(ProviderId providerId,
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700416 Device oldDevice,
417 Device newDevice, Timestamp newTimestamp) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700418 // We allow only certain attributes to trigger update
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700419 boolean propertiesChanged =
420 !Objects.equals(oldDevice.hwVersion(), newDevice.hwVersion()) ||
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700421 !Objects.equals(oldDevice.swVersion(), newDevice.swVersion()) ||
422 !Objects.equals(oldDevice.providerId(), newDevice.providerId());
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700423 boolean annotationsChanged =
424 !AnnotationsUtil.isEqual(oldDevice.annotations(), newDevice.annotations());
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700425
Thomas Vachuska56dbeb12014-10-22 16:40:44 -0700426 // Primary providers can respond to all changes, but ancillary ones
427 // should respond only to annotation changes.
428 if ((providerId.isAncillary() && annotationsChanged) ||
429 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700430 boolean replaced = devices.replace(newDevice.id(), oldDevice, newDevice);
431 if (!replaced) {
432 verify(replaced,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700433 "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
434 providerId, oldDevice, devices.get(newDevice.id())
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700435 , newDevice);
436 }
437 if (!providerId.isAncillary()) {
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700438 boolean wasOnline = availableDevices.contains(newDevice.id());
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700439 markOnline(newDevice.id(), newTimestamp);
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700440 if (!wasOnline) {
441 notifyDelegateIfNotNull(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, newDevice, null));
442 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700443 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700444
Thomas Vachuskadaaa42d2015-04-21 16:21:37 -0700445 return new DeviceEvent(DeviceEvent.Type.DEVICE_UPDATED, newDevice, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700446 }
447 return null;
448 }
449
450 @Override
451 public DeviceEvent markOffline(DeviceId deviceId) {
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700452 final Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700453 final DeviceEvent event = markOfflineInternal(deviceId, timestamp);
Madan Jampani25322532014-10-08 11:20:38 -0700454 if (event != null) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700455 log.info("Notifying peers of a device offline topology event for deviceId: {} {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700456 deviceId, timestamp);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800457 notifyPeers(new InternalDeviceOfflineEvent(deviceId, timestamp));
Madan Jampani25322532014-10-08 11:20:38 -0700458 }
459 return event;
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700460 }
461
462 private DeviceEvent markOfflineInternal(DeviceId deviceId, Timestamp timestamp) {
463
464 Map<ProviderId, DeviceDescriptions> providerDescs
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700465 = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700466
467 // locking device
468 synchronized (providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700469
470 // accept off-line if given timestamp is newer than
471 // the latest Timestamp from Primary provider
472 DeviceDescriptions primDescs = getPrimaryDescriptions(providerDescs);
473 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
474 if (timestamp.compareTo(lastTimestamp) <= 0) {
475 // outdated event ignore
476 return null;
477 }
478
479 offline.put(deviceId, timestamp);
480
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700481 Device device = devices.get(deviceId);
482 if (device == null) {
483 return null;
484 }
485 boolean removed = availableDevices.remove(deviceId);
486 if (removed) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700487 return new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device, null);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700488 }
489 return null;
490 }
491 }
492
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700493 /**
494 * Marks the device as available if the given timestamp is not outdated,
495 * compared to the time the device has been marked offline.
496 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700497 * @param deviceId identifier of the device
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700498 * @param timestamp of the event triggering this change.
499 * @return true if availability change request was accepted and changed the state
500 */
501 // Guarded by deviceDescs value (=Device lock)
502 private boolean markOnline(DeviceId deviceId, Timestamp timestamp) {
503 // accept on-line if given timestamp is newer than
504 // the latest offline request Timestamp
505 Timestamp offlineTimestamp = offline.get(deviceId);
506 if (offlineTimestamp == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700507 offlineTimestamp.compareTo(timestamp) < 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700508
509 offline.remove(deviceId);
510 return availableDevices.add(deviceId);
511 }
512 return false;
513 }
514
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700515 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700516 public synchronized List<DeviceEvent> updatePorts(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700517 DeviceId deviceId,
518 List<PortDescription> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700519
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800520 NodeId localNode = clusterService.getLocalNode().id();
521 // TODO: It might be negligible, but this will have negative impact to topology discovery performance,
522 // since it will trigger distributed store read.
523 // Also, it'll probably be better if side-way communication happened on ConfigurationProvider, etc.
524 // outside Device subsystem. so that we don't have to modify both Device and Link stores.
525 // If we don't care much about topology performance, then it might be OK.
526 NodeId deviceNode = mastershipService.getMasterFor(deviceId);
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700527
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800528 // Process port update only if we're the master of the device,
529 // otherwise signal the actual master.
530 List<DeviceEvent> deviceEvents = null;
531 if (localNode.equals(deviceNode)) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700532
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800533 final Timestamp newTimestamp;
534 try {
535 newTimestamp = deviceClockService.getTimestamp(deviceId);
536 } catch (IllegalStateException e) {
537 log.info("Timestamp was not available for device {}", deviceId);
538 log.debug(" discarding {}", portDescriptions);
539 // Failed to generate timestamp.
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700540
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800541 // Possible situation:
542 // Device connected and became master for short period of time,
543 // but lost mastership before this instance had the chance to
544 // retrieve term information.
545
546 // Information dropped here is expected to be recoverable by
547 // device probing after mastership change
548
549 return Collections.emptyList();
550 }
551 log.debug("timestamp for {} {}", deviceId, newTimestamp);
552
553 final Timestamped<List<PortDescription>> timestampedInput
554 = new Timestamped<>(portDescriptions, newTimestamp);
555 final Timestamped<List<PortDescription>> merged;
556
557 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
558
559 synchronized (device) {
560 deviceEvents = updatePortsInternal(providerId, deviceId, timestampedInput);
561 final DeviceDescriptions descs = device.get(providerId);
562 List<PortDescription> mergedList =
563 FluentIterable.from(portDescriptions)
564 .transform(new Function<PortDescription, PortDescription>() {
565 @Override
566 public PortDescription apply(PortDescription input) {
567 // lookup merged port description
568 return descs.getPortDesc(input.portNumber()).value();
569 }
570 }).toList();
571 merged = new Timestamped<List<PortDescription>>(mergedList, newTimestamp);
572 }
573
574 if (!deviceEvents.isEmpty()) {
575 log.info("Notifying peers of a ports update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700576 providerId, deviceId);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800577 notifyPeers(new InternalPortEvent(providerId, deviceId, merged));
578 }
579
580 } else {
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800581 // FIXME Temporary hack for NPE (ONOS-1171).
582 // Proper fix is to implement forwarding to master on ConfigProvider
583 // redo ONOS-490
584 if (deviceNode == null) {
585 // silently ignore
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800586 return Collections.emptyList();
HIGUCHI Yutadc2e7c22015-02-24 12:19:47 -0800587 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800588
589 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, portDescriptions);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800590
591 //TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700592 clusterCommunicator.unicast(portInjectedEvent, PORT_INJECTED, SERIALIZER::encode, deviceNode);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800593 /* error log:
594 log.warn("Failed to process injected ports of device id: {} " +
595 "(cluster messaging failed: {})",
596 deviceId, e);
597 */
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700598 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700599
Ayaka Koshibeeeb95102015-02-26 16:31:49 -0800600 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700601 }
602
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700603 private List<DeviceEvent> updatePortsInternal(ProviderId providerId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700604 DeviceId deviceId,
605 Timestamped<List<PortDescription>> portDescriptions) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700606
607 Device device = devices.get(deviceId);
608 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
609
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700610 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700611 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
612
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700613 List<DeviceEvent> events = new ArrayList<>();
614 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700615
616 if (isDeviceRemoved(deviceId, portDescriptions.timestamp())) {
617 log.debug("Ignoring outdated events: {}", portDescriptions);
618 return null;
619 }
620
621 DeviceDescriptions descs = descsMap.get(providerId);
622 // every provider must provide DeviceDescription.
623 checkArgument(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700624 "Device description for Device ID %s from Provider %s was not found",
625 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700626
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700627 Map<PortNumber, Port> ports = getPortMap(deviceId);
628
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700629 final Timestamp newTimestamp = portDescriptions.timestamp();
630
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700631 // Add new ports
632 Set<PortNumber> processed = new HashSet<>();
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700633 for (PortDescription portDescription : portDescriptions.value()) {
634 final PortNumber number = portDescription.portNumber();
635 processed.add(number);
636
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700637 final Port oldPort = ports.get(number);
638 final Port newPort;
639
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700640
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700641 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
642 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700643 newTimestamp.compareTo(existingPortDesc.timestamp()) >= 0) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700644 // on new port or valid update
645 // update description
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700646 descs.putPortDesc(new Timestamped<>(portDescription,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700647 portDescriptions.timestamp()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700648 newPort = composePort(device, number, descsMap);
649 } else {
650 // outdated event, ignored.
651 continue;
652 }
653
654 events.add(oldPort == null ?
655 createPort(device, newPort, ports) :
656 updatePort(device, oldPort, newPort, ports));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700657 }
658
659 events.addAll(pruneOldPorts(device, ports, processed));
660 }
661 return FluentIterable.from(events).filter(notNull()).toList();
662 }
663
664 // Creates a new port based on the port description adds it to the map and
665 // Returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700666 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700667 private DeviceEvent createPort(Device device, Port newPort,
668 Map<PortNumber, Port> ports) {
669 ports.put(newPort.number(), newPort);
670 return new DeviceEvent(PORT_ADDED, device, newPort);
671 }
672
673 // Checks if the specified port requires update and if so, it replaces the
674 // existing entry in the map and returns corresponding event.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700675 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700676 private DeviceEvent updatePort(Device device, Port oldPort,
677 Port newPort,
678 Map<PortNumber, Port> ports) {
679 if (oldPort.isEnabled() != newPort.isEnabled() ||
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700680 oldPort.type() != newPort.type() ||
681 oldPort.portSpeed() != newPort.portSpeed() ||
682 !AnnotationsUtil.isEqual(oldPort.annotations(), newPort.annotations())) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700683 ports.put(oldPort.number(), newPort);
684 return new DeviceEvent(PORT_UPDATED, device, newPort);
685 }
686 return null;
687 }
688
689 // Prunes the specified list of ports based on which ports are in the
690 // processed list and returns list of corresponding events.
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700691 // Guarded by deviceDescs value (=Device lock)
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700692 private List<DeviceEvent> pruneOldPorts(Device device,
693 Map<PortNumber, Port> ports,
694 Set<PortNumber> processed) {
695 List<DeviceEvent> events = new ArrayList<>();
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700696 Iterator<Entry<PortNumber, Port>> iterator = ports.entrySet().iterator();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700697 while (iterator.hasNext()) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700698 Entry<PortNumber, Port> e = iterator.next();
699 PortNumber portNumber = e.getKey();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700700 if (!processed.contains(portNumber)) {
Yuta HIGUCHI02649072014-10-15 23:28:20 -0700701 events.add(new DeviceEvent(PORT_REMOVED, device, e.getValue()));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700702 iterator.remove();
703 }
704 }
705 return events;
706 }
707
708 // Gets the map of ports for the specified device; if one does not already
709 // exist, it creates and registers a new one.
710 private ConcurrentMap<PortNumber, Port> getPortMap(DeviceId deviceId) {
711 return createIfAbsentUnchecked(devicePorts, deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700712 NewConcurrentHashMap.<PortNumber, Port>ifNeeded());
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700713 }
714
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700715 private Map<ProviderId, DeviceDescriptions> getOrCreateDeviceDescriptionsMap(
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700716 DeviceId deviceId) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700717 Map<ProviderId, DeviceDescriptions> r;
718 r = deviceDescs.get(deviceId);
719 if (r == null) {
720 r = new HashMap<ProviderId, DeviceDescriptions>();
721 final Map<ProviderId, DeviceDescriptions> concurrentlyAdded;
722 concurrentlyAdded = deviceDescs.putIfAbsent(deviceId, r);
723 if (concurrentlyAdded != null) {
724 r = concurrentlyAdded;
725 }
726 }
727 return r;
728 }
729
730 // Guarded by deviceDescs value (=Device lock)
731 private DeviceDescriptions getOrCreateProviderDeviceDescriptions(
732 Map<ProviderId, DeviceDescriptions> device,
733 ProviderId providerId, Timestamped<DeviceDescription> deltaDesc) {
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700734 synchronized (device) {
735 DeviceDescriptions r = device.get(providerId);
736 if (r == null) {
737 r = new DeviceDescriptions(deltaDesc);
738 device.put(providerId, r);
739 }
740 return r;
741 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700742 }
743
744 @Override
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700745 public synchronized DeviceEvent updatePortStatus(ProviderId providerId,
746 DeviceId deviceId,
747 PortDescription portDescription) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700748 final Timestamp newTimestamp;
749 try {
750 newTimestamp = deviceClockService.getTimestamp(deviceId);
751 } catch (IllegalStateException e) {
752 log.info("Timestamp was not available for device {}", deviceId);
753 log.debug(" discarding {}", portDescription);
754 // Failed to generate timestamp. Ignoring.
755 // See updatePorts comment
756 return null;
757 }
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700758 final Timestamped<PortDescription> deltaDesc
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700759 = new Timestamped<>(portDescription, newTimestamp);
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700760 final DeviceEvent event;
761 final Timestamped<PortDescription> mergedDesc;
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800762 final Map<ProviderId, DeviceDescriptions> device = getOrCreateDeviceDescriptionsMap(deviceId);
763 synchronized (device) {
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700764 event = updatePortStatusInternal(providerId, deviceId, deltaDesc);
Yuta HIGUCHI04c6b3f2014-11-07 14:47:01 -0800765 mergedDesc = device.get(providerId)
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700766 .getPortDesc(portDescription.portNumber());
Yuta HIGUCHI47c40882014-10-10 18:44:37 -0700767 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700768 if (event != null) {
Madan Jampani47c93732014-10-06 20:46:08 -0700769 log.info("Notifying peers of a port status update topology event for providerId: {} and deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700770 providerId, deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800771 notifyPeers(new InternalPortStatusEvent(providerId, deviceId, mergedDesc));
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700772 }
773 return event;
774 }
775
776 private DeviceEvent updatePortStatusInternal(ProviderId providerId, DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700777 Timestamped<PortDescription> deltaDesc) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700778 Device device = devices.get(deviceId);
779 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
780
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700781 Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700782 checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);
783
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700784 synchronized (descsMap) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700785
786 if (isDeviceRemoved(deviceId, deltaDesc.timestamp())) {
787 log.debug("Ignoring outdated event: {}", deltaDesc);
788 return null;
789 }
790
791 DeviceDescriptions descs = descsMap.get(providerId);
792 // assuming all providers must to give DeviceDescription
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700793 verify(descs != null,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700794 "Device description for Device ID %s from Provider %s was not found",
795 deviceId, providerId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700796
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700797 ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
798 final PortNumber number = deltaDesc.value().portNumber();
799 final Port oldPort = ports.get(number);
800 final Port newPort;
801
802 final Timestamped<PortDescription> existingPortDesc = descs.getPortDesc(number);
803 if (existingPortDesc == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700804 deltaDesc.isNewer(existingPortDesc)) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700805 // on new port or valid update
806 // update description
807 descs.putPortDesc(deltaDesc);
808 newPort = composePort(device, number, descsMap);
809 } else {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700810 // same or outdated event, ignored.
811 log.trace("ignore same or outdated {} >= {}", existingPortDesc, deltaDesc);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700812 return null;
813 }
814
815 if (oldPort == null) {
816 return createPort(device, newPort, ports);
817 } else {
818 return updatePort(device, oldPort, newPort, ports);
819 }
820 }
821 }
822
823 @Override
824 public List<Port> getPorts(DeviceId deviceId) {
825 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
826 if (ports == null) {
827 return Collections.emptyList();
828 }
829 return ImmutableList.copyOf(ports.values());
830 }
831
832 @Override
sangho538108b2015-04-08 14:29:20 -0700833 public DeviceEvent updatePortStatistics(ProviderId providerId, DeviceId deviceId,
834 Collection<PortStatistics> portStats) {
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700835 Map<PortNumber, PortStatistics> statsMap = devicePortStats.get(deviceId);
sangho538108b2015-04-08 14:29:20 -0700836 if (statsMap == null) {
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700837 statsMap = Maps.newHashMap();
sangho538108b2015-04-08 14:29:20 -0700838 }
839
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700840 for (PortStatistics stat : portStats) {
sangho538108b2015-04-08 14:29:20 -0700841 PortNumber portNumber = PortNumber.portNumber(stat.port());
842 statsMap.put(portNumber, stat);
843 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700844 devicePortStats.put(deviceId, statsMap);
845 return null; // new DeviceEvent(PORT_STATS_UPDATED, devices.get(deviceId), null);
sangho538108b2015-04-08 14:29:20 -0700846 }
847
848 @Override
849 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
sangho538108b2015-04-08 14:29:20 -0700850 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
851 if (portStats == null) {
852 return Collections.emptyList();
853 }
854 return ImmutableList.copyOf(portStats.values());
855 }
856
857 @Override
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700858 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
859 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
860 return ports == null ? null : ports.get(portNumber);
861 }
862
863 @Override
864 public boolean isAvailable(DeviceId deviceId) {
865 return availableDevices.contains(deviceId);
866 }
867
868 @Override
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700869 public synchronized DeviceEvent removeDevice(DeviceId deviceId) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800870 final NodeId myId = clusterService.getLocalNode().id();
871 NodeId master = mastershipService.getMasterFor(deviceId);
872
873 // if there exist a master, forward
874 // if there is no master, try to become one and process
875
876 boolean relinquishAtEnd = false;
877 if (master == null) {
878 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
879 if (myRole != MastershipRole.NONE) {
880 relinquishAtEnd = true;
881 }
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800882 log.debug("Temporarily requesting role for {} to remove", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800883 mastershipService.requestRoleFor(deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800884 MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampani7cdf3f12015-05-12 23:18:05 -0700885 if (term != null && myId.equals(term.master())) {
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800886 master = myId;
887 }
Yuta HIGUCHIe8252bb2014-10-22 09:41:01 -0700888 }
889
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800890 if (!myId.equals(master)) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800891 log.debug("{} has control of {}, forwarding remove request",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700892 master, deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800893
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800894 // TODO check unicast return value
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700895 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800896 /* error log:
897 log.error("Failed to forward {} remove request to {}", deviceId, master, e);
898 */
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800899
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800900 // event will be triggered after master processes it.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700901 return null;
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800902 }
903
904 // I have control..
905
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700906 Timestamp timestamp = deviceClockService.getTimestamp(deviceId);
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700907 DeviceEvent event = removeDeviceInternal(deviceId, timestamp);
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700908 if (event != null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800909 log.debug("Notifying peers of a device removed topology event for deviceId: {}",
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700910 deviceId);
Jonathan Hart7d656f42015-01-27 14:07:23 -0800911 notifyPeers(new InternalDeviceRemovedEvent(deviceId, timestamp));
Madan Jampani3fc72ed2014-10-08 12:50:27 -0700912 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800913 if (relinquishAtEnd) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -0800914 log.debug("Relinquishing temporary role acquired for {}", deviceId);
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -0800915 mastershipService.relinquishMastership(deviceId);
916 }
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700917 return event;
918 }
919
920 private DeviceEvent removeDeviceInternal(DeviceId deviceId,
921 Timestamp timestamp) {
922
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -0700923 Map<ProviderId, DeviceDescriptions> descs = getOrCreateDeviceDescriptionsMap(deviceId);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700924 synchronized (descs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700925 // accept removal request if given timestamp is newer than
926 // the latest Timestamp from Primary provider
927 DeviceDescriptions primDescs = getPrimaryDescriptions(descs);
928 Timestamp lastTimestamp = primDescs.getLatestTimestamp();
929 if (timestamp.compareTo(lastTimestamp) <= 0) {
930 // outdated event ignore
931 return null;
932 }
933 removalRequest.put(deviceId, timestamp);
934
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700935 Device device = devices.remove(deviceId);
936 // should DEVICE_REMOVED carry removed ports?
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700937 Map<PortNumber, Port> ports = devicePorts.get(deviceId);
938 if (ports != null) {
939 ports.clear();
940 }
941 markOfflineInternal(deviceId, timestamp);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700942 descs.clear();
943 return device == null ? null :
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700944 new DeviceEvent(DEVICE_REMOVED, device, null);
Yuta HIGUCHI0d6a5e62014-10-03 15:54:09 -0700945 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700946 }
947
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700948 /**
949 * Checks if given timestamp is superseded by removal request
950 * with more recent timestamp.
951 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700952 * @param deviceId identifier of a device
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700953 * @param timestampToCheck timestamp of an event to check
954 * @return true if device is already removed
955 */
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700956 private boolean isDeviceRemoved(DeviceId deviceId, Timestamp timestampToCheck) {
957 Timestamp removalTimestamp = removalRequest.get(deviceId);
958 if (removalTimestamp != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700959 removalTimestamp.compareTo(timestampToCheck) >= 0) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700960 // removalRequest is more recent
961 return true;
962 }
963 return false;
964 }
965
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700966 /**
967 * Returns a Device, merging description given from multiple Providers.
968 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700969 * @param deviceId device identifier
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700970 * @param providerDescs Collection of Descriptions from multiple providers
971 * @return Device instance
972 */
973 private Device composeDevice(DeviceId deviceId,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -0700974 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700975
Thomas Vachuska444eda62014-10-28 13:09:42 -0700976 checkArgument(!providerDescs.isEmpty(), "No device descriptions supplied");
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700977
978 ProviderId primary = pickPrimaryPID(providerDescs);
979
980 DeviceDescriptions desc = providerDescs.get(primary);
981
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -0700982 final DeviceDescription base = desc.getDeviceDesc().value();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700983 Type type = base.type();
984 String manufacturer = base.manufacturer();
985 String hwVersion = base.hwVersion();
986 String swVersion = base.swVersion();
987 String serialNumber = base.serialNumber();
alshabib7911a052014-10-16 17:49:37 -0700988 ChassisId chassisId = base.chassisId();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700989 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
990 annotations = merge(annotations, base.annotations());
991
992 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
993 if (e.getKey().equals(primary)) {
994 continue;
995 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -0800996 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -0700997 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -0700998 // Currently assuming there will never be a key conflict between
999 // providers
1000
1001 // annotation merging. not so efficient, should revisit later
1002 annotations = merge(annotations, e.getValue().getDeviceDesc().value().annotations());
1003 }
1004
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001005 return new DefaultDevice(primary, deviceId, type, manufacturer,
1006 hwVersion, swVersion, serialNumber,
1007 chassisId, annotations);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001008 }
1009
1010 /**
1011 * Returns a Port, merging description given from multiple Providers.
1012 *
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001013 * @param device device the port is on
1014 * @param number port number
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001015 * @param descsMap Collection of Descriptions from multiple providers
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001016 * @return Port instance
1017 */
1018 private Port composePort(Device device, PortNumber number,
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001019 Map<ProviderId, DeviceDescriptions> descsMap) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001020
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001021 ProviderId primary = pickPrimaryPID(descsMap);
1022 DeviceDescriptions primDescs = descsMap.get(primary);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001023 // if no primary, assume not enabled
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001024 boolean isEnabled = false;
1025 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
Ayaka Koshibeae541732015-05-19 13:37:27 -07001026 Timestamp newest = null;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001027 final Timestamped<PortDescription> portDesc = primDescs.getPortDesc(number);
1028 if (portDesc != null) {
1029 isEnabled = portDesc.value().isEnabled();
1030 annotations = merge(annotations, portDesc.value().annotations());
Ayaka Koshibeae541732015-05-19 13:37:27 -07001031 newest = portDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001032 }
Ayaka Koshibeae541732015-05-19 13:37:27 -07001033 Port updated = null;
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001034 for (Entry<ProviderId, DeviceDescriptions> e : descsMap.entrySet()) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001035 if (e.getKey().equals(primary)) {
1036 continue;
1037 }
Yuta HIGUCHI65934892014-12-04 17:47:44 -08001038 // Note: should keep track of Description timestamp in the future
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001039 // and only merge conflicting keys when timestamp is newer.
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001040 // Currently assuming there will never be a key conflict between
1041 // providers
1042
1043 // annotation merging. not so efficient, should revisit later
1044 final Timestamped<PortDescription> otherPortDesc = e.getValue().getPortDesc(number);
1045 if (otherPortDesc != null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001046 if (newest != null && newest.isNewerThan(otherPortDesc.timestamp())) {
1047 continue;
1048 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001049 annotations = merge(annotations, otherPortDesc.value().annotations());
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001050 PortDescription other = otherPortDesc.value();
1051 switch (other.type()) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001052 case OMS:
1053 OmsPortDescription omsPortDesc = (OmsPortDescription) otherPortDesc.value();
1054 updated = new OmsPort(device, number, isEnabled, omsPortDesc.minFrequency(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001055 omsPortDesc.maxFrequency(), omsPortDesc.grid(), annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001056 break;
1057 case OCH:
1058 OchPortDescription ochPortDesc = (OchPortDescription) otherPortDesc.value();
1059 updated = new OchPort(device, number, isEnabled, ochPortDesc.signalType(),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001060 ochPortDesc.isTunable(), ochPortDesc.lambda(), annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001061 break;
1062 case ODUCLT:
1063 OduCltPortDescription oduCltPortDesc = (OduCltPortDescription) otherPortDesc.value();
1064 updated = new OduCltPort(device, number, isEnabled, oduCltPortDesc.signalType(), annotations);
1065 break;
1066 default:
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001067 updated = new DefaultPort(
1068 device, number, isEnabled, other.type(), other.portSpeed(), annotations);
Ayaka Koshibeae541732015-05-19 13:37:27 -07001069 }
1070 newest = otherPortDesc.timestamp();
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001071 }
1072 }
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001073 if (portDesc == null) {
Ayaka Koshibeae541732015-05-19 13:37:27 -07001074 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
Marc De Leenheer4b18a232015-04-30 11:58:20 -07001075 }
Ayaka Koshibe74b55272015-05-28 15:16:04 -07001076 PortDescription current = portDesc.value();
1077 return updated == null
1078 ? new DefaultPort(device, number, isEnabled, current.type(), current.portSpeed(), annotations)
1079 : updated;
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001080 }
1081
1082 /**
1083 * @return primary ProviderID, or randomly chosen one if none exists
1084 */
1085 private ProviderId pickPrimaryPID(
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001086 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001087 ProviderId fallBackPrimary = null;
1088 for (Entry<ProviderId, DeviceDescriptions> e : providerDescs.entrySet()) {
1089 if (!e.getKey().isAncillary()) {
1090 return e.getKey();
1091 } else if (fallBackPrimary == null) {
1092 // pick randomly as a fallback in case there is no primary
1093 fallBackPrimary = e.getKey();
1094 }
1095 }
1096 return fallBackPrimary;
1097 }
1098
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001099 private DeviceDescriptions getPrimaryDescriptions(
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001100 Map<ProviderId, DeviceDescriptions> providerDescs) {
Yuta HIGUCHIc35efac2014-10-06 14:43:53 -07001101 ProviderId pid = pickPrimaryPID(providerDescs);
1102 return providerDescs.get(pid);
1103 }
1104
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001105 private void unicastMessage(NodeId recipient, MessageSubject subject, Object event) throws IOException {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001106 clusterCommunicator.unicast(event, subject, SERIALIZER::encode, recipient);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001107 }
1108
Jonathan Hart7d656f42015-01-27 14:07:23 -08001109 private void broadcastMessage(MessageSubject subject, Object event) {
Madan Jampani2bfa94c2015-04-11 05:03:49 -07001110 clusterCommunicator.broadcast(event, subject, SERIALIZER::encode);
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001111 }
Madan Jampani47c93732014-10-06 20:46:08 -07001112
Jonathan Hart7d656f42015-01-27 14:07:23 -08001113 private void notifyPeers(InternalDeviceEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001114 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001115 }
1116
Jonathan Hart7d656f42015-01-27 14:07:23 -08001117 private void notifyPeers(InternalDeviceOfflineEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001118 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
Madan Jampani25322532014-10-08 11:20:38 -07001119 }
1120
Jonathan Hart7d656f42015-01-27 14:07:23 -08001121 private void notifyPeers(InternalDeviceRemovedEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001122 broadcastMessage(GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001123 }
1124
Jonathan Hart7d656f42015-01-27 14:07:23 -08001125 private void notifyPeers(InternalPortEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001126 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
Madan Jampani47c93732014-10-06 20:46:08 -07001127 }
1128
Jonathan Hart7d656f42015-01-27 14:07:23 -08001129 private void notifyPeers(InternalPortStatusEvent event) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001130 broadcastMessage(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1131 }
1132
1133 private void notifyPeer(NodeId recipient, InternalDeviceEvent event) {
1134 try {
1135 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, event);
1136 } catch (IOException e) {
1137 log.error("Failed to send" + event + " to " + recipient, e);
1138 }
1139 }
1140
1141 private void notifyPeer(NodeId recipient, InternalDeviceOfflineEvent event) {
1142 try {
1143 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_OFFLINE, event);
1144 } catch (IOException e) {
1145 log.error("Failed to send" + event + " to " + recipient, e);
1146 }
1147 }
1148
1149 private void notifyPeer(NodeId recipient, InternalDeviceRemovedEvent event) {
1150 try {
1151 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.DEVICE_REMOVED, event);
1152 } catch (IOException e) {
1153 log.error("Failed to send" + event + " to " + recipient, e);
1154 }
1155 }
1156
1157 private void notifyPeer(NodeId recipient, InternalPortEvent event) {
1158 try {
1159 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_UPDATE, event);
1160 } catch (IOException e) {
1161 log.error("Failed to send" + event + " to " + recipient, e);
1162 }
1163 }
1164
1165 private void notifyPeer(NodeId recipient, InternalPortStatusEvent event) {
1166 try {
1167 unicastMessage(recipient, GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, event);
1168 } catch (IOException e) {
1169 log.error("Failed to send" + event + " to " + recipient, e);
1170 }
1171 }
1172
1173 private DeviceAntiEntropyAdvertisement createAdvertisement() {
1174 final NodeId self = clusterService.getLocalNode().id();
1175
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001176 final int numDevices = deviceDescs.size();
1177 Map<DeviceFragmentId, Timestamp> adDevices = new HashMap<>(numDevices);
1178 final int portsPerDevice = 8; // random factor to minimize reallocation
1179 Map<PortFragmentId, Timestamp> adPorts = new HashMap<>(numDevices * portsPerDevice);
1180 Map<DeviceId, Timestamp> adOffline = new HashMap<>(numDevices);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001181
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001182 deviceDescs.forEach((deviceId, devDescs) -> {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001183
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001184 // for each Device...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001185 synchronized (devDescs) {
1186
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001187 // send device offline timestamp
1188 Timestamp lOffline = this.offline.get(deviceId);
1189 if (lOffline != null) {
1190 adOffline.put(deviceId, lOffline);
1191 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001192
1193 for (Entry<ProviderId, DeviceDescriptions>
1194 prov : devDescs.entrySet()) {
1195
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001196 // for each Provider Descriptions...
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001197 final ProviderId provId = prov.getKey();
1198 final DeviceDescriptions descs = prov.getValue();
1199
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001200 adDevices.put(new DeviceFragmentId(deviceId, provId),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001201 descs.getDeviceDesc().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001202
1203 for (Entry<PortNumber, Timestamped<PortDescription>>
1204 portDesc : descs.getPortDescs().entrySet()) {
1205
1206 final PortNumber number = portDesc.getKey();
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001207 adPorts.put(new PortFragmentId(deviceId, provId, number),
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001208 portDesc.getValue().timestamp());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001209 }
1210 }
1211 }
Yuta HIGUCHIb6cfac32014-11-25 13:37:27 -08001212 });
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001213
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001214 return new DeviceAntiEntropyAdvertisement(self, adDevices, adPorts, adOffline);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001215 }
1216
1217 /**
1218 * Responds to anti-entropy advertisement message.
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001219 * <p/>
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001220 * Notify sender about out-dated information using regular replication message.
1221 * Send back advertisement to sender if not in sync.
1222 *
1223 * @param advertisement to respond to
1224 */
1225 private void handleAdvertisement(DeviceAntiEntropyAdvertisement advertisement) {
1226
1227 final NodeId sender = advertisement.sender();
1228
1229 Map<DeviceFragmentId, Timestamp> devAds = new HashMap<>(advertisement.deviceFingerPrints());
1230 Map<PortFragmentId, Timestamp> portAds = new HashMap<>(advertisement.ports());
1231 Map<DeviceId, Timestamp> offlineAds = new HashMap<>(advertisement.offline());
1232
1233 // Fragments to request
1234 Collection<DeviceFragmentId> reqDevices = new ArrayList<>();
1235 Collection<PortFragmentId> reqPorts = new ArrayList<>();
1236
Yuta HIGUCHIbf71dff2014-10-14 16:02:33 -07001237 for (Entry<DeviceId, Map<ProviderId, DeviceDescriptions>> de : deviceDescs.entrySet()) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001238 final DeviceId deviceId = de.getKey();
1239 final Map<ProviderId, DeviceDescriptions> lDevice = de.getValue();
1240
1241 synchronized (lDevice) {
1242 // latestTimestamp across provider
1243 // Note: can be null initially
1244 Timestamp localLatest = offline.get(deviceId);
1245
1246 // handle device Ads
1247 for (Entry<ProviderId, DeviceDescriptions> prov : lDevice.entrySet()) {
1248 final ProviderId provId = prov.getKey();
1249 final DeviceDescriptions lDeviceDescs = prov.getValue();
1250
1251 final DeviceFragmentId devFragId = new DeviceFragmentId(deviceId, provId);
1252
1253
1254 Timestamped<DeviceDescription> lProvDevice = lDeviceDescs.getDeviceDesc();
1255 Timestamp advDevTimestamp = devAds.get(devFragId);
1256
Jonathan Hart403ea932015-02-20 16:23:00 -08001257 if (advDevTimestamp == null || lProvDevice.isNewerThan(
1258 advDevTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001259 // remote does not have it or outdated, suggest
1260 notifyPeer(sender, new InternalDeviceEvent(provId, deviceId, lProvDevice));
1261 } else if (!lProvDevice.timestamp().equals(advDevTimestamp)) {
1262 // local is outdated, request
1263 reqDevices.add(devFragId);
1264 }
1265
1266 // handle port Ads
1267 for (Entry<PortNumber, Timestamped<PortDescription>>
1268 pe : lDeviceDescs.getPortDescs().entrySet()) {
1269
1270 final PortNumber num = pe.getKey();
1271 final Timestamped<PortDescription> lPort = pe.getValue();
1272
1273 final PortFragmentId portFragId = new PortFragmentId(deviceId, provId, num);
1274
1275 Timestamp advPortTimestamp = portAds.get(portFragId);
Jonathan Hart403ea932015-02-20 16:23:00 -08001276 if (advPortTimestamp == null || lPort.isNewerThan(
1277 advPortTimestamp)) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001278 // remote does not have it or outdated, suggest
1279 notifyPeer(sender, new InternalPortStatusEvent(provId, deviceId, lPort));
1280 } else if (!lPort.timestamp().equals(advPortTimestamp)) {
1281 // local is outdated, request
1282 log.trace("need update {} < {}", lPort.timestamp(), advPortTimestamp);
1283 reqPorts.add(portFragId);
1284 }
1285
1286 // remove port Ad already processed
1287 portAds.remove(portFragId);
1288 } // end local port loop
1289
1290 // remove device Ad already processed
1291 devAds.remove(devFragId);
1292
1293 // find latest and update
1294 final Timestamp providerLatest = lDeviceDescs.getLatestTimestamp();
1295 if (localLatest == null ||
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001296 providerLatest.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001297 localLatest = providerLatest;
1298 }
1299 } // end local provider loop
1300
1301 // checking if remote timestamp is more recent.
1302 Timestamp rOffline = offlineAds.get(deviceId);
1303 if (rOffline != null &&
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001304 rOffline.compareTo(localLatest) > 0) {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001305 // remote offline timestamp suggests that the
1306 // device is off-line
1307 markOfflineInternal(deviceId, rOffline);
1308 }
1309
1310 Timestamp lOffline = offline.get(deviceId);
1311 if (lOffline != null && rOffline == null) {
1312 // locally offline, but remote is online, suggest offline
1313 notifyPeer(sender, new InternalDeviceOfflineEvent(deviceId, lOffline));
1314 }
1315
1316 // remove device offline Ad already processed
1317 offlineAds.remove(deviceId);
1318 } // end local device loop
1319 } // device lock
1320
1321 // If there is any Ads left, request them
1322 log.trace("Ads left {}, {}", devAds, portAds);
1323 reqDevices.addAll(devAds.keySet());
1324 reqPorts.addAll(portAds.keySet());
1325
1326 if (reqDevices.isEmpty() && reqPorts.isEmpty()) {
1327 log.trace("Nothing to request to remote peer {}", sender);
1328 return;
1329 }
1330
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001331 log.debug("Need to sync {} {}", reqDevices, reqPorts);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001332
1333 // 2-way Anti-Entropy for now
1334 try {
1335 unicastMessage(sender, DEVICE_ADVERTISE, createAdvertisement());
1336 } catch (IOException e) {
1337 log.error("Failed to send response advertisement to " + sender, e);
1338 }
1339
1340// Sketch of 3-way Anti-Entropy
1341// DeviceAntiEntropyRequest request = new DeviceAntiEntropyRequest(self, reqDevices, reqPorts);
1342// ClusterMessage message = new ClusterMessage(
1343// clusterService.getLocalNode().id(),
1344// GossipDeviceStoreMessageSubjects.DEVICE_REQUEST,
1345// SERIALIZER.encode(request));
1346//
1347// try {
1348// clusterCommunicator.unicast(message, advertisement.sender());
1349// } catch (IOException e) {
1350// log.error("Failed to send advertisement reply to "
1351// + advertisement.sender(), e);
1352// }
Madan Jampani47c93732014-10-06 20:46:08 -07001353 }
1354
Madan Jampani255a58b2014-10-09 12:08:20 -07001355 private void notifyDelegateIfNotNull(DeviceEvent event) {
1356 if (event != null) {
1357 notifyDelegate(event);
1358 }
1359 }
1360
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001361 private final class SendAdvertisementTask implements Runnable {
1362
1363 @Override
1364 public void run() {
1365 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001366 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001367 return;
1368 }
1369
1370 try {
1371 final NodeId self = clusterService.getLocalNode().id();
1372 Set<ControllerNode> nodes = clusterService.getNodes();
1373
1374 ImmutableList<NodeId> nodeIds = FluentIterable.from(nodes)
1375 .transform(toNodeId())
1376 .toList();
1377
1378 if (nodeIds.size() == 1 && nodeIds.get(0).equals(self)) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001379 log.trace("No other peers in the cluster.");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001380 return;
1381 }
1382
1383 NodeId peer;
1384 do {
1385 int idx = RandomUtils.nextInt(0, nodeIds.size());
1386 peer = nodeIds.get(idx);
1387 } while (peer.equals(self));
1388
1389 DeviceAntiEntropyAdvertisement ad = createAdvertisement();
1390
1391 if (Thread.currentThread().isInterrupted()) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001392 log.debug("Interrupted, quitting");
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001393 return;
1394 }
1395
1396 try {
1397 unicastMessage(peer, DEVICE_ADVERTISE, ad);
1398 } catch (IOException e) {
Yuta HIGUCHI78f3a0a2014-10-16 17:24:20 -07001399 log.debug("Failed to send anti-entropy advertisement to {}", peer);
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001400 return;
1401 }
1402 } catch (Exception e) {
1403 // catch all Exception to avoid Scheduled task being suppressed.
1404 log.error("Exception thrown while sending advertisement", e);
1405 }
1406 }
1407 }
1408
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001409 private final class InternalDeviceEventListener
1410 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001411 @Override
1412 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001413 log.debug("Received device update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001414 InternalDeviceEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001415
Madan Jampani47c93732014-10-06 20:46:08 -07001416 ProviderId providerId = event.providerId();
1417 DeviceId deviceId = event.deviceId();
1418 Timestamped<DeviceDescription> deviceDescription = event.deviceDescription();
Madan Jampani25322532014-10-08 11:20:38 -07001419
Madan Jampani2af244a2015-02-22 13:12:01 -08001420 try {
1421 notifyDelegateIfNotNull(createOrUpdateDeviceInternal(providerId, deviceId, deviceDescription));
1422 } catch (Exception e) {
1423 log.warn("Exception thrown handling device update", e);
1424 }
Madan Jampani47c93732014-10-06 20:46:08 -07001425 }
1426 }
1427
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001428 private final class InternalDeviceOfflineEventListener
1429 implements ClusterMessageHandler {
Madan Jampani25322532014-10-08 11:20:38 -07001430 @Override
1431 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001432 log.debug("Received device offline event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001433 InternalDeviceOfflineEvent event = SERIALIZER.decode(message.payload());
Madan Jampani25322532014-10-08 11:20:38 -07001434
1435 DeviceId deviceId = event.deviceId();
1436 Timestamp timestamp = event.timestamp();
1437
Madan Jampani2af244a2015-02-22 13:12:01 -08001438 try {
1439 notifyDelegateIfNotNull(markOfflineInternal(deviceId, timestamp));
1440 } catch (Exception e) {
1441 log.warn("Exception thrown handling device offline", e);
1442 }
Madan Jampani25322532014-10-08 11:20:38 -07001443 }
1444 }
1445
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001446 private final class InternalRemoveRequestListener
1447 implements ClusterMessageHandler {
1448 @Override
1449 public void handle(ClusterMessage message) {
1450 log.debug("Received device remove request from peer: {}", message.sender());
1451 DeviceId did = SERIALIZER.decode(message.payload());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001452
Madan Jampani2af244a2015-02-22 13:12:01 -08001453 try {
1454 removeDevice(did);
1455 } catch (Exception e) {
1456 log.warn("Exception thrown handling device remove", e);
1457 }
Yuta HIGUCHI53afd5b2014-11-03 18:03:08 -08001458 }
1459 }
1460
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001461 private final class InternalDeviceRemovedEventListener
1462 implements ClusterMessageHandler {
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001463 @Override
1464 public void handle(ClusterMessage message) {
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001465 log.debug("Received device removed event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001466 InternalDeviceRemovedEvent event = SERIALIZER.decode(message.payload());
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001467
1468 DeviceId deviceId = event.deviceId();
1469 Timestamp timestamp = event.timestamp();
1470
Madan Jampani2af244a2015-02-22 13:12:01 -08001471 try {
1472 notifyDelegateIfNotNull(removeDeviceInternal(deviceId, timestamp));
1473 } catch (Exception e) {
1474 log.warn("Exception thrown handling device removed", e);
1475 }
Madan Jampani3fc72ed2014-10-08 12:50:27 -07001476 }
1477 }
1478
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001479 private final class InternalPortEventListener
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 update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001485 InternalPortEvent 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<List<PortDescription>> portDescriptions = event.portDescriptions();
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 notifyDelegate(updatePortsInternal(providerId, deviceId, portDescriptions));
1499 } catch (Exception e) {
1500 log.warn("Exception thrown handling port update", e);
1501 }
Madan Jampani47c93732014-10-06 20:46:08 -07001502 }
1503 }
1504
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001505 private final class InternalPortStatusEventListener
1506 implements ClusterMessageHandler {
Madan Jampani47c93732014-10-06 20:46:08 -07001507 @Override
1508 public void handle(ClusterMessage message) {
1509
Yuta HIGUCHIcc8e96e2014-10-31 17:48:09 -07001510 log.debug("Received port status update event from peer: {}", message.sender());
Yuta HIGUCHI80d56592014-11-25 15:11:13 -08001511 InternalPortStatusEvent event = SERIALIZER.decode(message.payload());
Madan Jampani47c93732014-10-06 20:46:08 -07001512
1513 ProviderId providerId = event.providerId();
1514 DeviceId deviceId = event.deviceId();
1515 Timestamped<PortDescription> portDescription = event.portDescription();
1516
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001517 if (getDevice(deviceId) == null) {
Yuta HIGUCHI1a012722014-11-20 15:21:41 -08001518 log.debug("{} not found on this node yet, ignoring.", deviceId);
Yuta HIGUCHI20c0e972014-10-31 15:22:33 -07001519 // Note: dropped information will be recovered by anti-entropy
1520 return;
1521 }
1522
Madan Jampani2af244a2015-02-22 13:12:01 -08001523 try {
1524 notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
1525 } catch (Exception e) {
1526 log.warn("Exception thrown handling port update", e);
1527 }
Madan Jampani47c93732014-10-06 20:46:08 -07001528 }
1529 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001530
1531 private final class InternalDeviceAdvertisementListener
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001532 implements ClusterMessageHandler {
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001533 @Override
1534 public void handle(ClusterMessage message) {
Yuta HIGUCHIfaf9e1c2014-11-20 00:31:29 -08001535 log.trace("Received Device Anti-Entropy advertisement from peer: {}", message.sender());
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001536 DeviceAntiEntropyAdvertisement advertisement = SERIALIZER.decode(message.payload());
Madan Jampani2af244a2015-02-22 13:12:01 -08001537 try {
1538 handleAdvertisement(advertisement);
1539 } catch (Exception e) {
1540 log.warn("Exception thrown handling Device advertisements.", e);
1541 }
Yuta HIGUCHI9ee60f62014-10-09 10:00:01 -07001542 }
1543 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001544
1545 private final class DeviceInjectedEventListener
1546 implements ClusterMessageHandler {
1547 @Override
1548 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001549 log.debug("Received injected device event from peer: {}", message.sender());
1550 DeviceInjectedEvent event = SERIALIZER.decode(message.payload());
1551
1552 ProviderId providerId = event.providerId();
1553 DeviceId deviceId = event.deviceId();
1554 DeviceDescription deviceDescription = event.deviceDescription();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001555 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1556 // workaround for ONOS-1208
1557 log.warn("Not ready to accept update. Dropping {}", deviceDescription);
1558 return;
1559 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001560
Madan Jampani2af244a2015-02-22 13:12:01 -08001561 try {
1562 createOrUpdateDevice(providerId, deviceId, deviceDescription);
1563 } catch (Exception e) {
1564 log.warn("Exception thrown handling device injected event.", e);
1565 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001566 }
1567 }
1568
1569 private final class PortInjectedEventListener
1570 implements ClusterMessageHandler {
1571 @Override
1572 public void handle(ClusterMessage message) {
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001573 log.debug("Received injected port event from peer: {}", message.sender());
1574 PortInjectedEvent event = SERIALIZER.decode(message.payload());
1575
1576 ProviderId providerId = event.providerId();
1577 DeviceId deviceId = event.deviceId();
1578 List<PortDescription> portDescriptions = event.portDescriptions();
HIGUCHI Yuta62334412015-03-13 13:23:05 -07001579 if (!deviceClockService.isTimestampAvailable(deviceId)) {
1580 // workaround for ONOS-1208
1581 log.warn("Not ready to accept update. Dropping {}", portDescriptions);
1582 return;
1583 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001584
Madan Jampani2af244a2015-02-22 13:12:01 -08001585 try {
1586 updatePorts(providerId, deviceId, portDescriptions);
1587 } catch (Exception e) {
1588 log.warn("Exception thrown handling port injected event.", e);
1589 }
Marc De Leenheerb473b9d2015-02-06 15:21:03 -08001590 }
1591 }
Thomas Vachuskafdbc4c22015-05-29 15:53:01 -07001592
1593 private class InternalPortStatsListener
1594 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
1595 @Override
1596 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
1597 if (event.type() == PUT) {
1598 Device device = devices.get(event.key());
1599 if (device != null) {
1600 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
1601 }
1602 }
1603 }
1604 }
Yuta HIGUCHI67a527f2014-10-02 22:23:54 -07001605}