blob: 680f0a097a74896b2be9e40db67254a907ce3d45 [file] [log] [blame]
Madan Jampanifc8aced2015-08-27 11:06:12 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Madan Jampanifc8aced2015-08-27 11:06:12 -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 */
16package org.onosproject.store.device.impl;
17
Ray Milkey2bf5ea72017-06-01 09:03:34 -070018import java.util.Collection;
19import java.util.Collections;
20import java.util.List;
21import java.util.Map;
22import java.util.Map.Entry;
23import java.util.Objects;
24import java.util.Optional;
25import java.util.Set;
26import java.util.concurrent.TimeUnit;
27import java.util.concurrent.atomic.AtomicReference;
28import java.util.stream.Collectors;
29import java.util.stream.Stream;
30
Madan Jampanifc8aced2015-08-27 11:06:12 -070031import org.apache.felix.scr.annotations.Activate;
Madan Jampanifc8aced2015-08-27 11:06:12 -070032import org.apache.felix.scr.annotations.Deactivate;
33import org.apache.felix.scr.annotations.Reference;
34import org.apache.felix.scr.annotations.ReferenceCardinality;
35import org.apache.felix.scr.annotations.Service;
36import org.onlab.packet.ChassisId;
37import org.onlab.util.KryoNamespace;
Madan Jampanifc8aced2015-08-27 11:06:12 -070038import org.onosproject.cluster.ClusterService;
39import org.onosproject.cluster.NodeId;
40import org.onosproject.mastership.MastershipService;
41import org.onosproject.mastership.MastershipTermService;
42import org.onosproject.net.Annotations;
43import org.onosproject.net.AnnotationsUtil;
44import org.onosproject.net.DefaultAnnotations;
45import org.onosproject.net.DefaultDevice;
46import org.onosproject.net.DefaultPort;
47import org.onosproject.net.Device;
Jian Li11599162016-01-15 15:46:16 -080048import org.onosproject.net.Device.Type;
Madan Jampanifc8aced2015-08-27 11:06:12 -070049import org.onosproject.net.DeviceId;
50import org.onosproject.net.MastershipRole;
Madan Jampanifc8aced2015-08-27 11:06:12 -070051import org.onosproject.net.Port;
52import org.onosproject.net.PortNumber;
Madan Jampanifc8aced2015-08-27 11:06:12 -070053import org.onosproject.net.device.DefaultPortStatistics;
54import 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;
Madan Jampanifc8aced2015-08-27 11:06:12 -070059import org.onosproject.net.device.PortDescription;
60import org.onosproject.net.device.PortStatistics;
61import org.onosproject.net.provider.ProviderId;
62import org.onosproject.store.AbstractStore;
63import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
64import org.onosproject.store.impl.MastershipBasedTimestamp;
65import org.onosproject.store.serializers.KryoNamespaces;
Madan Jampanifc8aced2015-08-27 11:06:12 -070066import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
67import org.onosproject.store.service.DistributedSet;
68import org.onosproject.store.service.EventuallyConsistentMap;
69import org.onosproject.store.service.EventuallyConsistentMapEvent;
Jian Li11599162016-01-15 15:46:16 -080070import org.onosproject.store.service.EventuallyConsistentMapListener;
Madan Jampanifc8aced2015-08-27 11:06:12 -070071import org.onosproject.store.service.Serializer;
72import org.onosproject.store.service.SetEvent;
73import org.onosproject.store.service.SetEventListener;
Madan Jampanifc8aced2015-08-27 11:06:12 -070074import org.onosproject.store.service.StorageService;
Jian Li11599162016-01-15 15:46:16 -080075import org.onosproject.store.service.WallClockTimestamp;
Madan Jampanifc8aced2015-08-27 11:06:12 -070076import org.slf4j.Logger;
77
Ray Milkey2bf5ea72017-06-01 09:03:34 -070078import com.google.common.collect.ImmutableList;
79import com.google.common.collect.Iterables;
80import com.google.common.collect.Lists;
81import com.google.common.collect.Maps;
82import com.google.common.collect.Sets;
83import com.google.common.util.concurrent.Futures;
Jian Li11599162016-01-15 15:46:16 -080084
85import static com.google.common.base.Preconditions.checkArgument;
86import static com.google.common.base.Verify.verify;
87import static org.onosproject.net.DefaultAnnotations.merge;
88import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_ADDED;
89import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED;
90import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
91import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_UPDATED;
92import static org.onosproject.net.device.DeviceEvent.Type.PORT_ADDED;
93import static org.onosproject.net.device.DeviceEvent.Type.PORT_STATS_UPDATED;
94import static org.onosproject.net.device.DeviceEvent.Type.PORT_UPDATED;
Madan Jampanifc8aced2015-08-27 11:06:12 -070095import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
Jian Li11599162016-01-15 15:46:16 -080096import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
97import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.REMOVE;
98import static org.slf4j.LoggerFactory.getLogger;
Madan Jampanifc8aced2015-08-27 11:06:12 -070099
100/**
101 * Manages the inventory of devices using a {@code EventuallyConsistentMap}.
102 */
Jian Li11599162016-01-15 15:46:16 -0800103//@Component(immediate = true, enabled = false)
Madan Jampanifc8aced2015-08-27 11:06:12 -0700104@Service
105public class ECDeviceStore
106 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
107 implements DeviceStore {
108
109 private final Logger log = getLogger(getClass());
110
111 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
112
113 private final Map<DeviceId, Device> devices = Maps.newConcurrentMap();
114 private final Map<DeviceId, Map<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
115 Set<DeviceId> pendingAvailableChangeUpdates = Sets.newConcurrentHashSet();
116
117 private EventuallyConsistentMap<DeviceKey, DeviceDescription> deviceDescriptions;
118 private EventuallyConsistentMap<PortKey, PortDescription> portDescriptions;
119 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
120 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
121
122 private DistributedSet<DeviceId> availableDevices;
123
124 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
125 protected StorageService storageService;
126
127 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
128 protected MastershipService mastershipService;
129
130 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
131 protected MastershipTermService mastershipTermService;
132
133 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
134 protected DeviceClockService deviceClockService;
135
136 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
137 protected ClusterCommunicationService clusterCommunicator;
138
139 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
140 protected ClusterService clusterService;
141
142 private NodeId localNodeId;
143 private EventuallyConsistentMapListener<DeviceKey, DeviceDescription> deviceUpdateListener =
144 new InternalDeviceChangeEventListener();
145 private EventuallyConsistentMapListener<PortKey, PortDescription> portUpdateListener =
146 new InternalPortChangeEventListener();
147 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> portStatsListener =
148 new InternalPortStatsListener();
149 private final SetEventListener<DeviceId> deviceStatusTracker =
150 new InternalDeviceStatusTracker();
151
Jordan Haltermanc6c6ef22017-08-20 17:11:41 -0700152 protected static final Serializer SERIALIZER = Serializer.using(
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700153 KryoNamespace.newBuilder()
Madan Jampanifc8aced2015-08-27 11:06:12 -0700154 .register(DistributedStoreSerializers.STORE_COMMON)
155 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700156 .build("ECDevice"));
Madan Jampanifc8aced2015-08-27 11:06:12 -0700157
158 protected static final KryoNamespace.Builder SERIALIZER_BUILDER = KryoNamespace.newBuilder()
159 .register(KryoNamespaces.API)
160 .register(DeviceKey.class)
161 .register(PortKey.class)
162 .register(DeviceKey.class)
163 .register(PortKey.class)
164 .register(MastershipBasedTimestamp.class);
165
166 @Activate
167 public void activate() {
168 localNodeId = clusterService.getLocalNode().id();
169
170 deviceDescriptions = storageService.<DeviceKey, DeviceDescription>eventuallyConsistentMapBuilder()
171 .withName("onos-device-descriptions")
172 .withSerializer(SERIALIZER_BUILDER)
173 .withTimestampProvider((k, v) -> {
174 try {
175 return deviceClockService.getTimestamp(k.deviceId());
176 } catch (IllegalStateException e) {
177 return null;
178 }
179 }).build();
180
181 portDescriptions = storageService.<PortKey, PortDescription>eventuallyConsistentMapBuilder()
182 .withName("onos-port-descriptions")
183 .withSerializer(SERIALIZER_BUILDER)
184 .withTimestampProvider((k, v) -> {
185 try {
186 return deviceClockService.getTimestamp(k.deviceId());
187 } catch (IllegalStateException e) {
188 return null;
189 }
190 }).build();
191
192 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
193 .withName("onos-port-stats")
194 .withSerializer(SERIALIZER_BUILDER)
195 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
196 .withTimestampProvider((k, v) -> new WallClockTimestamp())
197 .withTombstonesDisabled()
198 .build();
199
200 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
201 eventuallyConsistentMapBuilder()
202 .withName("onos-port-stats-delta")
203 .withSerializer(SERIALIZER_BUILDER)
204 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
205 .withTimestampProvider((k, v) -> new WallClockTimestamp())
206 .withTombstonesDisabled()
207 .build();
208
Madan Jampanifc8aced2015-08-27 11:06:12 -0700209 availableDevices = storageService.<DeviceId>setBuilder()
210 .withName("onos-online-devices")
211 .withSerializer(Serializer.using(KryoNamespaces.API))
Madan Jampanifc8aced2015-08-27 11:06:12 -0700212 .withRelaxedReadConsistency()
Madan Jampani538be742016-02-10 14:55:38 -0800213 .build()
214 .asDistributedSet();
Madan Jampanifc8aced2015-08-27 11:06:12 -0700215
216 deviceDescriptions.addListener(deviceUpdateListener);
217 portDescriptions.addListener(portUpdateListener);
218 devicePortStats.addListener(portStatsListener);
219 availableDevices.addListener(deviceStatusTracker);
220 log.info("Started");
221 }
222
223 @Deactivate
224 public void deactivate() {
225 devicePortStats.removeListener(portStatsListener);
226 deviceDescriptions.removeListener(deviceUpdateListener);
227 portDescriptions.removeListener(portUpdateListener);
228 availableDevices.removeListener(deviceStatusTracker);
229 devicePortStats.destroy();
230 devicePortDeltaStats.destroy();
231 deviceDescriptions.destroy();
232 portDescriptions.destroy();
233 devices.clear();
234 devicePorts.clear();
Madan Jampanifc8aced2015-08-27 11:06:12 -0700235 log.info("Stopped");
236 }
237
238 @Override
239 public Iterable<Device> getDevices() {
240 return devices.values();
241 }
242
243 @Override
244 public int getDeviceCount() {
245 return devices.size();
246 }
247
248 @Override
mskala0d0c6832017-07-12 11:21:23 +0200249 public int getAvailableDeviceCount() {
250 return availableDevices.size();
251 }
252
253 @Override
Madan Jampanifc8aced2015-08-27 11:06:12 -0700254 public Device getDevice(DeviceId deviceId) {
255 return devices.get(deviceId);
256 }
257
helenyrwufd296b62016-06-22 17:43:02 -0700258 // FIXME handle deviceDescription.isDefaultAvailable()=false case properly.
Madan Jampanifc8aced2015-08-27 11:06:12 -0700259 @Override
260 public DeviceEvent createOrUpdateDevice(ProviderId providerId,
261 DeviceId deviceId,
262 DeviceDescription deviceDescription) {
263 NodeId master = mastershipService.getMasterFor(deviceId);
264 if (localNodeId.equals(master)) {
265 deviceDescriptions.put(new DeviceKey(providerId, deviceId), deviceDescription);
266 return refreshDeviceCache(providerId, deviceId);
267 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800268 return null;
Madan Jampanifc8aced2015-08-27 11:06:12 -0700269 }
270 }
271
272 private DeviceEvent refreshDeviceCache(ProviderId providerId, DeviceId deviceId) {
273 AtomicReference<DeviceEvent.Type> eventType = new AtomicReference<>();
274 Device device = devices.compute(deviceId, (k, existingDevice) -> {
275 Device newDevice = composeDevice(deviceId);
276 if (existingDevice == null) {
277 eventType.set(DEVICE_ADDED);
278 } else {
279 // We allow only certain attributes to trigger update
280 boolean propertiesChanged =
281 !Objects.equals(existingDevice.hwVersion(), newDevice.hwVersion()) ||
282 !Objects.equals(existingDevice.swVersion(), newDevice.swVersion()) ||
283 !Objects.equals(existingDevice.providerId(), newDevice.providerId());
284 boolean annotationsChanged =
285 !AnnotationsUtil.isEqual(existingDevice.annotations(), newDevice.annotations());
286
287 // Primary providers can respond to all changes, but ancillary ones
288 // should respond only to annotation changes.
289 if ((providerId.isAncillary() && annotationsChanged) ||
290 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
291 boolean replaced = devices.replace(deviceId, existingDevice, newDevice);
292 verify(replaced, "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
293 providerId, existingDevice, devices.get(deviceId), newDevice);
294 eventType.set(DEVICE_UPDATED);
295 }
296 }
297 return newDevice;
298 });
299 if (eventType.get() != null && !providerId.isAncillary()) {
300 markOnline(deviceId);
301 }
302 return eventType.get() != null ? new DeviceEvent(eventType.get(), device) : null;
303 }
304
305 /**
306 * Returns the primary providerId for a device.
307 * @param deviceId device identifier
308 * @return primary providerId
309 */
310 private Set<ProviderId> getAllProviders(DeviceId deviceId) {
311 return deviceDescriptions.keySet()
312 .stream()
313 .filter(deviceKey -> deviceKey.deviceId().equals(deviceId))
314 .map(deviceKey -> deviceKey.providerId())
315 .collect(Collectors.toSet());
316 }
317
318 /**
319 * Returns the identifier for all providers for a device.
320 * @param deviceId device identifier
321 * @return set of provider identifiers
322 */
323 private ProviderId getPrimaryProviderId(DeviceId deviceId) {
324 Set<ProviderId> allProviderIds = getAllProviders(deviceId);
325 return allProviderIds.stream()
326 .filter(p -> !p.isAncillary())
327 .findFirst()
328 .orElse(Iterables.getFirst(allProviderIds, null));
329 }
330
331 /**
332 * Returns a Device, merging descriptions from multiple Providers.
333 *
334 * @param deviceId device identifier
335 * @return Device instance
336 */
337 private Device composeDevice(DeviceId deviceId) {
338
339 ProviderId primaryProviderId = getPrimaryProviderId(deviceId);
340 DeviceDescription primaryDeviceDescription =
341 deviceDescriptions.get(new DeviceKey(primaryProviderId, deviceId));
342
343 Type type = primaryDeviceDescription.type();
344 String manufacturer = primaryDeviceDescription.manufacturer();
345 String hwVersion = primaryDeviceDescription.hwVersion();
346 String swVersion = primaryDeviceDescription.swVersion();
347 String serialNumber = primaryDeviceDescription.serialNumber();
348 ChassisId chassisId = primaryDeviceDescription.chassisId();
349 DefaultAnnotations annotations = mergeAnnotations(deviceId);
350
351 return new DefaultDevice(primaryProviderId, deviceId, type, manufacturer,
352 hwVersion, swVersion, serialNumber,
353 chassisId, annotations);
354 }
355
356 private DeviceEvent purgeDeviceCache(DeviceId deviceId) {
357 Device removedDevice = devices.remove(deviceId);
358 if (removedDevice != null) {
359 getAllProviders(deviceId).forEach(p -> deviceDescriptions.remove(new DeviceKey(p, deviceId)));
360 return new DeviceEvent(DEVICE_REMOVED, removedDevice);
361 }
362 return null;
363 }
364
helenyrwufd296b62016-06-22 17:43:02 -0700365 // FIXME publicization of markOnline -- trigger some action independently?
366 public boolean markOnline(DeviceId deviceId) {
367 if (devices.containsKey(deviceId)) {
368 return availableDevices.add(deviceId);
369 }
370 log.warn("Device {} does not exist in store", deviceId);
371 return false;
Madan Jampanifc8aced2015-08-27 11:06:12 -0700372 }
373
374 @Override
375 public DeviceEvent markOffline(DeviceId deviceId) {
376 availableDevices.remove(deviceId);
377 // set update listener will raise the event.
378 return null;
379 }
380
381 @Override
382 public List<DeviceEvent> updatePorts(ProviderId providerId,
383 DeviceId deviceId,
384 List<PortDescription> descriptions) {
385 NodeId master = mastershipService.getMasterFor(deviceId);
386 List<DeviceEvent> deviceEvents = null;
387 if (localNodeId.equals(master)) {
388 descriptions.forEach(description -> {
389 PortKey portKey = new PortKey(providerId, deviceId, description.portNumber());
390 portDescriptions.put(portKey, description);
391 });
392 deviceEvents = refreshDevicePortCache(providerId, deviceId, Optional.empty());
393 } else {
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700394 return Collections.emptyList();
Madan Jampanifc8aced2015-08-27 11:06:12 -0700395 }
396 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
397 }
398
399 private List<DeviceEvent> refreshDevicePortCache(ProviderId providerId,
400 DeviceId deviceId,
401 Optional<PortNumber> portNumber) {
402 Device device = devices.get(deviceId);
403 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
404 List<DeviceEvent> events = Lists.newArrayList();
405
406 Map<PortNumber, Port> ports = devicePorts.computeIfAbsent(deviceId, key -> Maps.newConcurrentMap());
407 List<PortDescription> descriptions = Lists.newArrayList();
408 portDescriptions.entrySet().forEach(e -> {
409 PortKey key = e.getKey();
410 PortDescription value = e.getValue();
411 if (key.deviceId().equals(deviceId) && key.providerId().equals(providerId)) {
412 if (portNumber.isPresent()) {
413 if (portNumber.get().equals(key.portNumber())) {
414 descriptions.add(value);
415 }
416 } else {
417 descriptions.add(value);
418 }
419 }
420 });
421
422 for (PortDescription description : descriptions) {
423 final PortNumber number = description.portNumber();
424 ports.compute(number, (k, existingPort) -> {
425 Port newPort = composePort(device, number);
426 if (existingPort == null) {
427 events.add(new DeviceEvent(PORT_ADDED, device, newPort));
428 } else {
429 if (existingPort.isEnabled() != newPort.isEnabled() ||
430 existingPort.type() != newPort.type() ||
431 existingPort.portSpeed() != newPort.portSpeed() ||
432 !AnnotationsUtil.isEqual(existingPort.annotations(), newPort.annotations())) {
433 events.add(new DeviceEvent(PORT_UPDATED, device, newPort));
434 }
435 }
436 return newPort;
437 });
438 }
439
440 return events;
441 }
442
443 /**
444 * Returns a Port, merging descriptions from multiple Providers.
445 *
446 * @param device device the port is on
447 * @param number port number
448 * @return Port instance
449 */
450 private Port composePort(Device device, PortNumber number) {
451
452 Map<ProviderId, PortDescription> descriptions = Maps.newHashMap();
453 portDescriptions.entrySet().forEach(entry -> {
454 PortKey portKey = entry.getKey();
455 if (portKey.deviceId().equals(device.id()) && portKey.portNumber().equals(number)) {
456 descriptions.put(portKey.providerId(), entry.getValue());
457 }
458 });
459 ProviderId primary = getPrimaryProviderId(device.id());
460 PortDescription primaryDescription = descriptions.get(primary);
461
462 // if no primary, assume not enabled
463 boolean isEnabled = false;
464 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
465 if (primaryDescription != null) {
466 isEnabled = primaryDescription.isEnabled();
467 annotations = merge(annotations, primaryDescription.annotations());
468 }
469 Port updated = null;
470 for (Entry<ProviderId, PortDescription> e : descriptions.entrySet()) {
471 if (e.getKey().equals(primary)) {
472 continue;
473 }
474 annotations = merge(annotations, e.getValue().annotations());
475 updated = buildTypedPort(device, number, isEnabled, e.getValue(), annotations);
476 }
477 if (primaryDescription == null) {
478 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
479 }
480 return updated == null
481 ? buildTypedPort(device, number, isEnabled, primaryDescription, annotations)
482 : updated;
483 }
484
485 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
486 PortDescription description, Annotations annotations) {
Madan Jampanifc8aced2015-08-27 11:06:12 -0700487 return new DefaultPort(device, number, isEnabled, description.type(),
488 description.portSpeed(), annotations);
Madan Jampanifc8aced2015-08-27 11:06:12 -0700489 }
490
491 @Override
492 public DeviceEvent updatePortStatus(ProviderId providerId,
493 DeviceId deviceId,
494 PortDescription portDescription) {
495 portDescriptions.put(new PortKey(providerId, deviceId, portDescription.portNumber()), portDescription);
496 List<DeviceEvent> events =
497 refreshDevicePortCache(providerId, deviceId, Optional.of(portDescription.portNumber()));
498 return Iterables.getFirst(events, null);
499 }
500
501 @Override
502 public List<Port> getPorts(DeviceId deviceId) {
503 return ImmutableList.copyOf(devicePorts.getOrDefault(deviceId, Maps.newHashMap()).values());
504 }
505
506 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700507 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
508 DeviceId deviceId) {
509
510 return portDescriptions.entrySet().stream()
511 .filter(e -> e.getKey().providerId().equals(pid))
512 .map(Map.Entry::getValue);
513 }
514
515 @Override
Madan Jampanifc8aced2015-08-27 11:06:12 -0700516 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
517 return devicePorts.getOrDefault(deviceId, Maps.newHashMap()).get(portNumber);
518 }
519
520 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700521 public PortDescription getPortDescription(ProviderId pid,
522 DeviceId deviceId,
523 PortNumber portNumber) {
524 return portDescriptions.get(new PortKey(pid, deviceId, portNumber));
525 }
526
527 @Override
Madan Jampanifc8aced2015-08-27 11:06:12 -0700528 public DeviceEvent updatePortStatistics(ProviderId providerId,
529 DeviceId deviceId,
530 Collection<PortStatistics> newStatsCollection) {
531
532 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
533 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
534 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
535
536 if (prvStatsMap != null) {
537 for (PortStatistics newStats : newStatsCollection) {
538 PortNumber port = PortNumber.portNumber(newStats.port());
539 PortStatistics prvStats = prvStatsMap.get(port);
540 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
541 PortStatistics deltaStats = builder.build();
542 if (prvStats != null) {
543 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
544 }
545 deltaStatsMap.put(port, deltaStats);
546 newStatsMap.put(port, newStats);
547 }
548 } else {
549 for (PortStatistics newStats : newStatsCollection) {
550 PortNumber port = PortNumber.portNumber(newStats.port());
551 newStatsMap.put(port, newStats);
552 }
553 }
554 devicePortDeltaStats.put(deviceId, deltaStatsMap);
555 devicePortStats.put(deviceId, newStatsMap);
556 // DeviceEvent returns null because of InternalPortStatsListener usage
557 return null;
558 }
559
560 /**
561 * Calculate delta statistics by subtracting previous from new statistics.
562 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700563 * @param deviceId device indentifier
564 * @param prvStats previous port statistics
565 * @param newStats new port statistics
Madan Jampanifc8aced2015-08-27 11:06:12 -0700566 * @return PortStatistics
567 */
568 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
569 // calculate time difference
570 long deltaStatsSec, deltaStatsNano;
571 if (newStats.durationNano() < prvStats.durationNano()) {
572 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
573 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
574 } else {
575 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
576 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
577 }
578 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
579 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
580 .setPort(newStats.port())
581 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
582 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
583 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
584 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
585 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
586 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
587 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
588 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
589 .setDurationSec(deltaStatsSec)
590 .setDurationNano(deltaStatsNano)
591 .build();
592 return deltaStats;
593 }
594
595 @Override
596 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
597 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
598 if (portStats == null) {
599 return Collections.emptyList();
600 }
601 return ImmutableList.copyOf(portStats.values());
602 }
603
604 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530605 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
606 Map<PortNumber, PortStatistics> portStatsMap = devicePortStats.get(deviceId);
607 if (portStatsMap == null) {
608 return null;
609 }
610 PortStatistics portStats = portStatsMap.get(portNumber);
611 return portStats;
612 }
613
614 @Override
Madan Jampanifc8aced2015-08-27 11:06:12 -0700615 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
616 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
617 if (portStats == null) {
618 return Collections.emptyList();
619 }
620 return ImmutableList.copyOf(portStats.values());
621 }
622
623 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530624 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
625 Map<PortNumber, PortStatistics> portStatsMap = devicePortDeltaStats.get(deviceId);
626 if (portStatsMap == null) {
627 return null;
628 }
629 PortStatistics portStats = portStatsMap.get(portNumber);
630 return portStats;
631 }
632
633 @Override
Madan Jampanifc8aced2015-08-27 11:06:12 -0700634 public boolean isAvailable(DeviceId deviceId) {
635 return availableDevices.contains(deviceId);
636 }
637
638 @Override
639 public Iterable<Device> getAvailableDevices() {
640 return Iterables.filter(Iterables.transform(availableDevices, devices::get), d -> d != null);
641 }
642
643 @Override
644 public DeviceEvent removeDevice(DeviceId deviceId) {
645 NodeId master = mastershipService.getMasterFor(deviceId);
646 // if there exist a master, forward
647 // if there is no master, try to become one and process
648 boolean relinquishAtEnd = false;
649 if (master == null) {
650 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
651 if (myRole != MastershipRole.NONE) {
652 relinquishAtEnd = true;
653 }
654 log.debug("Temporarily requesting role for {} to remove", deviceId);
655 MastershipRole role = Futures.getUnchecked(mastershipService.requestRoleFor(deviceId));
656 if (role == MastershipRole.MASTER) {
657 master = localNodeId;
658 }
659 }
660
661 if (!localNodeId.equals(master)) {
662 log.debug("{} has control of {}, forwarding remove request",
663 master, deviceId);
664
665 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master)
666 .whenComplete((r, e) -> {
667 if (e != null) {
668 log.error("Failed to forward {} remove request to its master", deviceId, e);
669 }
670 });
671 return null;
672 }
673
674 // I have control..
675 DeviceEvent event = null;
676 final DeviceKey deviceKey = new DeviceKey(getPrimaryProviderId(deviceId), deviceId);
677 DeviceDescription removedDeviceDescription =
678 deviceDescriptions.remove(deviceKey);
679 if (removedDeviceDescription != null) {
680 event = purgeDeviceCache(deviceId);
681 }
682
683 if (relinquishAtEnd) {
684 log.debug("Relinquishing temporary role acquired for {}", deviceId);
685 mastershipService.relinquishMastership(deviceId);
686 }
687 return event;
688 }
689
Madan Jampanifc8aced2015-08-27 11:06:12 -0700690 private DefaultAnnotations mergeAnnotations(DeviceId deviceId) {
691 ProviderId primaryProviderId = getPrimaryProviderId(deviceId);
692 DeviceDescription primaryDeviceDescription =
693 deviceDescriptions.get(new DeviceKey(primaryProviderId, deviceId));
694 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
695 annotations = merge(annotations, primaryDeviceDescription.annotations());
696 for (ProviderId providerId : getAllProviders(deviceId)) {
697 if (!providerId.equals(primaryProviderId)) {
698 annotations = merge(annotations,
699 deviceDescriptions.get(new DeviceKey(providerId, deviceId)).annotations());
700 }
701 }
702 return annotations;
703 }
704
705 private class InternalDeviceStatusTracker implements SetEventListener<DeviceId> {
706 @Override
707 public void event(SetEvent<DeviceId> event) {
708 final DeviceId deviceId = event.entry();
709 final Device device = devices.get(deviceId);
710 if (device != null) {
711 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device));
712 } else {
713 pendingAvailableChangeUpdates.add(deviceId);
714 }
715 }
716 }
717
718 private class InternalDeviceChangeEventListener
719 implements EventuallyConsistentMapListener<DeviceKey, DeviceDescription> {
720 @Override
721 public void event(EventuallyConsistentMapEvent<DeviceKey, DeviceDescription> event) {
722 DeviceId deviceId = event.key().deviceId();
723 ProviderId providerId = event.key().providerId();
724 if (event.type() == PUT) {
725 notifyDelegate(refreshDeviceCache(providerId, deviceId));
726 if (pendingAvailableChangeUpdates.remove(deviceId)) {
727 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, devices.get(deviceId)));
728 }
729 } else if (event.type() == REMOVE) {
730 notifyDelegate(purgeDeviceCache(deviceId));
731 }
732 }
733 }
734
735 private class InternalPortChangeEventListener
736 implements EventuallyConsistentMapListener<PortKey, PortDescription> {
737 @Override
738 public void event(EventuallyConsistentMapEvent<PortKey, PortDescription> event) {
739 DeviceId deviceId = event.key().deviceId();
740 ProviderId providerId = event.key().providerId();
741 PortNumber portNumber = event.key().portNumber();
742 if (event.type() == PUT) {
743 if (devices.containsKey(deviceId)) {
744 List<DeviceEvent> events = refreshDevicePortCache(providerId, deviceId, Optional.of(portNumber));
745 for (DeviceEvent deviceEvent : events) {
746 notifyDelegate(deviceEvent);
747 }
748 }
749 } else if (event.type() == REMOVE) {
750 log.warn("Unexpected port removed event");
751 }
752 }
753 }
754
755 private class InternalPortStatsListener
756 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
757 @Override
758 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
759 if (event.type() == PUT) {
760 Device device = devices.get(event.key());
761 if (device != null) {
Thomas Vachuskad4955ae2016-08-23 14:56:37 -0700762 notifyDelegate(new DeviceEvent(PORT_STATS_UPDATED, device));
Madan Jampanifc8aced2015-08-27 11:06:12 -0700763 }
764 }
765 }
766 }
Ray Milkey2bf5ea72017-06-01 09:03:34 -0700767}