blob: 725e3ca07613078a6fd7a6e441e890d11be02325 [file] [log] [blame]
Madan Jampanifc8aced2015-08-27 11:06:12 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
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
Jian Li11599162016-01-15 15:46:16 -080018import com.google.common.collect.ImmutableList;
19import com.google.common.collect.Iterables;
20import com.google.common.collect.Lists;
21import com.google.common.collect.Maps;
22import com.google.common.collect.Sets;
23import com.google.common.util.concurrent.Futures;
Madan Jampanifc8aced2015-08-27 11:06:12 -070024import org.apache.felix.scr.annotations.Activate;
Madan Jampanifc8aced2015-08-27 11:06:12 -070025import org.apache.felix.scr.annotations.Deactivate;
26import org.apache.felix.scr.annotations.Reference;
27import org.apache.felix.scr.annotations.ReferenceCardinality;
28import org.apache.felix.scr.annotations.Service;
29import org.onlab.packet.ChassisId;
30import org.onlab.util.KryoNamespace;
31import org.onlab.util.SharedExecutors;
32import org.onosproject.cluster.ClusterService;
33import org.onosproject.cluster.NodeId;
34import org.onosproject.mastership.MastershipService;
35import org.onosproject.mastership.MastershipTermService;
36import org.onosproject.net.Annotations;
37import org.onosproject.net.AnnotationsUtil;
38import org.onosproject.net.DefaultAnnotations;
39import org.onosproject.net.DefaultDevice;
40import org.onosproject.net.DefaultPort;
41import org.onosproject.net.Device;
Jian Li11599162016-01-15 15:46:16 -080042import org.onosproject.net.Device.Type;
Madan Jampanifc8aced2015-08-27 11:06:12 -070043import org.onosproject.net.DeviceId;
44import org.onosproject.net.MastershipRole;
45import org.onosproject.net.OchPort;
46import org.onosproject.net.OduCltPort;
47import org.onosproject.net.OmsPort;
48import org.onosproject.net.Port;
49import org.onosproject.net.PortNumber;
Madan Jampanifc8aced2015-08-27 11:06:12 -070050import org.onosproject.net.device.DefaultPortStatistics;
51import org.onosproject.net.device.DeviceClockService;
52import org.onosproject.net.device.DeviceDescription;
53import org.onosproject.net.device.DeviceEvent;
54import org.onosproject.net.device.DeviceStore;
55import org.onosproject.net.device.DeviceStoreDelegate;
56import org.onosproject.net.device.OchPortDescription;
57import org.onosproject.net.device.OduCltPortDescription;
58import org.onosproject.net.device.OmsPortDescription;
59import 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;
HIGUCHI Yutae7290652016-05-18 11:29:01 -070066import org.onosproject.store.serializers.StoreSerializer;
Madan Jampanifc8aced2015-08-27 11:06:12 -070067import org.onosproject.store.serializers.custom.DistributedStoreSerializers;
68import org.onosproject.store.service.DistributedSet;
69import org.onosproject.store.service.EventuallyConsistentMap;
70import org.onosproject.store.service.EventuallyConsistentMapEvent;
Jian Li11599162016-01-15 15:46:16 -080071import org.onosproject.store.service.EventuallyConsistentMapListener;
Madan Jampanifc8aced2015-08-27 11:06:12 -070072import org.onosproject.store.service.Serializer;
73import org.onosproject.store.service.SetEvent;
74import org.onosproject.store.service.SetEventListener;
Madan Jampanifc8aced2015-08-27 11:06:12 -070075import org.onosproject.store.service.StorageService;
Jian Li11599162016-01-15 15:46:16 -080076import org.onosproject.store.service.WallClockTimestamp;
Madan Jampanifc8aced2015-08-27 11:06:12 -070077import org.slf4j.Logger;
78
Jian Li11599162016-01-15 15:46:16 -080079import java.util.Collection;
80import java.util.Collections;
81import java.util.List;
82import java.util.Map;
83import java.util.Map.Entry;
84import java.util.Objects;
85import java.util.Optional;
86import java.util.Set;
87import java.util.concurrent.TimeUnit;
88import java.util.concurrent.atomic.AtomicReference;
89import java.util.stream.Collectors;
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -070090import java.util.stream.Stream;
Jian Li11599162016-01-15 15:46:16 -080091
92import static com.google.common.base.Preconditions.checkArgument;
93import static com.google.common.base.Verify.verify;
94import static org.onosproject.net.DefaultAnnotations.merge;
95import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_ADDED;
96import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED;
97import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_REMOVED;
98import static org.onosproject.net.device.DeviceEvent.Type.DEVICE_UPDATED;
99import static org.onosproject.net.device.DeviceEvent.Type.PORT_ADDED;
100import static org.onosproject.net.device.DeviceEvent.Type.PORT_STATS_UPDATED;
101import static org.onosproject.net.device.DeviceEvent.Type.PORT_UPDATED;
Madan Jampanifc8aced2015-08-27 11:06:12 -0700102import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_INJECTED;
103import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.DEVICE_REMOVE_REQ;
104import static org.onosproject.store.device.impl.GossipDeviceStoreMessageSubjects.PORT_INJECTED;
Jian Li11599162016-01-15 15:46:16 -0800105import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT;
106import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.REMOVE;
107import static org.slf4j.LoggerFactory.getLogger;
Madan Jampanifc8aced2015-08-27 11:06:12 -0700108
109/**
110 * Manages the inventory of devices using a {@code EventuallyConsistentMap}.
111 */
Jian Li11599162016-01-15 15:46:16 -0800112//@Component(immediate = true, enabled = false)
Madan Jampanifc8aced2015-08-27 11:06:12 -0700113@Service
114public class ECDeviceStore
115 extends AbstractStore<DeviceEvent, DeviceStoreDelegate>
116 implements DeviceStore {
117
118 private final Logger log = getLogger(getClass());
119
120 private static final String DEVICE_NOT_FOUND = "Device with ID %s not found";
121
122 private final Map<DeviceId, Device> devices = Maps.newConcurrentMap();
123 private final Map<DeviceId, Map<PortNumber, Port>> devicePorts = Maps.newConcurrentMap();
124 Set<DeviceId> pendingAvailableChangeUpdates = Sets.newConcurrentHashSet();
125
126 private EventuallyConsistentMap<DeviceKey, DeviceDescription> deviceDescriptions;
127 private EventuallyConsistentMap<PortKey, PortDescription> portDescriptions;
128 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortStats;
129 private EventuallyConsistentMap<DeviceId, Map<PortNumber, PortStatistics>> devicePortDeltaStats;
130
131 private DistributedSet<DeviceId> availableDevices;
132
133 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
134 protected StorageService storageService;
135
136 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
137 protected MastershipService mastershipService;
138
139 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
140 protected MastershipTermService mastershipTermService;
141
142 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
143 protected DeviceClockService deviceClockService;
144
145 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
146 protected ClusterCommunicationService clusterCommunicator;
147
148 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
149 protected ClusterService clusterService;
150
151 private NodeId localNodeId;
152 private EventuallyConsistentMapListener<DeviceKey, DeviceDescription> deviceUpdateListener =
153 new InternalDeviceChangeEventListener();
154 private EventuallyConsistentMapListener<PortKey, PortDescription> portUpdateListener =
155 new InternalPortChangeEventListener();
156 private final EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> portStatsListener =
157 new InternalPortStatsListener();
158 private final SetEventListener<DeviceId> deviceStatusTracker =
159 new InternalDeviceStatusTracker();
160
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700161 protected static final StoreSerializer SERIALIZER = StoreSerializer.using(
162 KryoNamespace.newBuilder()
Madan Jampanifc8aced2015-08-27 11:06:12 -0700163 .register(DistributedStoreSerializers.STORE_COMMON)
164 .nextId(DistributedStoreSerializers.STORE_CUSTOM_BEGIN)
165 .register(DeviceInjectedEvent.class)
166 .register(PortInjectedEvent.class)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700167 .build("ECDevice"));
Madan Jampanifc8aced2015-08-27 11:06:12 -0700168
169 protected static final KryoNamespace.Builder SERIALIZER_BUILDER = KryoNamespace.newBuilder()
170 .register(KryoNamespaces.API)
171 .register(DeviceKey.class)
172 .register(PortKey.class)
173 .register(DeviceKey.class)
174 .register(PortKey.class)
175 .register(MastershipBasedTimestamp.class);
176
177 @Activate
178 public void activate() {
179 localNodeId = clusterService.getLocalNode().id();
180
181 deviceDescriptions = storageService.<DeviceKey, DeviceDescription>eventuallyConsistentMapBuilder()
182 .withName("onos-device-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 portDescriptions = storageService.<PortKey, PortDescription>eventuallyConsistentMapBuilder()
193 .withName("onos-port-descriptions")
194 .withSerializer(SERIALIZER_BUILDER)
195 .withTimestampProvider((k, v) -> {
196 try {
197 return deviceClockService.getTimestamp(k.deviceId());
198 } catch (IllegalStateException e) {
199 return null;
200 }
201 }).build();
202
203 devicePortStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>eventuallyConsistentMapBuilder()
204 .withName("onos-port-stats")
205 .withSerializer(SERIALIZER_BUILDER)
206 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
207 .withTimestampProvider((k, v) -> new WallClockTimestamp())
208 .withTombstonesDisabled()
209 .build();
210
211 devicePortDeltaStats = storageService.<DeviceId, Map<PortNumber, PortStatistics>>
212 eventuallyConsistentMapBuilder()
213 .withName("onos-port-stats-delta")
214 .withSerializer(SERIALIZER_BUILDER)
215 .withAntiEntropyPeriod(5, TimeUnit.SECONDS)
216 .withTimestampProvider((k, v) -> new WallClockTimestamp())
217 .withTombstonesDisabled()
218 .build();
219
220 clusterCommunicator.addSubscriber(DEVICE_INJECTED,
221 SERIALIZER::decode,
222 this::injectDevice,
223 SERIALIZER::encode,
224 SharedExecutors.getPoolThreadExecutor());
225
226 clusterCommunicator.addSubscriber(PORT_INJECTED,
227 SERIALIZER::decode,
228 this::injectPort,
229 SERIALIZER::encode,
230 SharedExecutors.getPoolThreadExecutor());
231
232 availableDevices = storageService.<DeviceId>setBuilder()
233 .withName("onos-online-devices")
234 .withSerializer(Serializer.using(KryoNamespaces.API))
Madan Jampanifc8aced2015-08-27 11:06:12 -0700235 .withRelaxedReadConsistency()
Madan Jampani538be742016-02-10 14:55:38 -0800236 .build()
237 .asDistributedSet();
Madan Jampanifc8aced2015-08-27 11:06:12 -0700238
239 deviceDescriptions.addListener(deviceUpdateListener);
240 portDescriptions.addListener(portUpdateListener);
241 devicePortStats.addListener(portStatsListener);
242 availableDevices.addListener(deviceStatusTracker);
243 log.info("Started");
244 }
245
246 @Deactivate
247 public void deactivate() {
248 devicePortStats.removeListener(portStatsListener);
249 deviceDescriptions.removeListener(deviceUpdateListener);
250 portDescriptions.removeListener(portUpdateListener);
251 availableDevices.removeListener(deviceStatusTracker);
252 devicePortStats.destroy();
253 devicePortDeltaStats.destroy();
254 deviceDescriptions.destroy();
255 portDescriptions.destroy();
256 devices.clear();
257 devicePorts.clear();
258 clusterCommunicator.removeSubscriber(DEVICE_INJECTED);
259 clusterCommunicator.removeSubscriber(PORT_INJECTED);
260 log.info("Stopped");
261 }
262
263 @Override
264 public Iterable<Device> getDevices() {
265 return devices.values();
266 }
267
268 @Override
269 public int getDeviceCount() {
270 return devices.size();
271 }
272
273 @Override
274 public Device getDevice(DeviceId deviceId) {
275 return devices.get(deviceId);
276 }
277
278 @Override
279 public DeviceEvent createOrUpdateDevice(ProviderId providerId,
280 DeviceId deviceId,
281 DeviceDescription deviceDescription) {
282 NodeId master = mastershipService.getMasterFor(deviceId);
283 if (localNodeId.equals(master)) {
284 deviceDescriptions.put(new DeviceKey(providerId, deviceId), deviceDescription);
285 return refreshDeviceCache(providerId, deviceId);
286 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800287 // Only forward for ConfigProvider
288 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800289 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800290 return null;
291 }
Madan Jampanifc8aced2015-08-27 11:06:12 -0700292 DeviceInjectedEvent deviceInjectedEvent = new DeviceInjectedEvent(providerId, deviceId, deviceDescription);
293 return Futures.getUnchecked(
294 clusterCommunicator.sendAndReceive(deviceInjectedEvent,
295 DEVICE_INJECTED,
296 SERIALIZER::encode,
297 SERIALIZER::decode,
298 master));
299 }
300 }
301
302 private DeviceEvent refreshDeviceCache(ProviderId providerId, DeviceId deviceId) {
303 AtomicReference<DeviceEvent.Type> eventType = new AtomicReference<>();
304 Device device = devices.compute(deviceId, (k, existingDevice) -> {
305 Device newDevice = composeDevice(deviceId);
306 if (existingDevice == null) {
307 eventType.set(DEVICE_ADDED);
308 } else {
309 // We allow only certain attributes to trigger update
310 boolean propertiesChanged =
311 !Objects.equals(existingDevice.hwVersion(), newDevice.hwVersion()) ||
312 !Objects.equals(existingDevice.swVersion(), newDevice.swVersion()) ||
313 !Objects.equals(existingDevice.providerId(), newDevice.providerId());
314 boolean annotationsChanged =
315 !AnnotationsUtil.isEqual(existingDevice.annotations(), newDevice.annotations());
316
317 // Primary providers can respond to all changes, but ancillary ones
318 // should respond only to annotation changes.
319 if ((providerId.isAncillary() && annotationsChanged) ||
320 (!providerId.isAncillary() && (propertiesChanged || annotationsChanged))) {
321 boolean replaced = devices.replace(deviceId, existingDevice, newDevice);
322 verify(replaced, "Replacing devices cache failed. PID:%s [expected:%s, found:%s, new=%s]",
323 providerId, existingDevice, devices.get(deviceId), newDevice);
324 eventType.set(DEVICE_UPDATED);
325 }
326 }
327 return newDevice;
328 });
329 if (eventType.get() != null && !providerId.isAncillary()) {
330 markOnline(deviceId);
331 }
332 return eventType.get() != null ? new DeviceEvent(eventType.get(), device) : null;
333 }
334
335 /**
336 * Returns the primary providerId for a device.
337 * @param deviceId device identifier
338 * @return primary providerId
339 */
340 private Set<ProviderId> getAllProviders(DeviceId deviceId) {
341 return deviceDescriptions.keySet()
342 .stream()
343 .filter(deviceKey -> deviceKey.deviceId().equals(deviceId))
344 .map(deviceKey -> deviceKey.providerId())
345 .collect(Collectors.toSet());
346 }
347
348 /**
349 * Returns the identifier for all providers for a device.
350 * @param deviceId device identifier
351 * @return set of provider identifiers
352 */
353 private ProviderId getPrimaryProviderId(DeviceId deviceId) {
354 Set<ProviderId> allProviderIds = getAllProviders(deviceId);
355 return allProviderIds.stream()
356 .filter(p -> !p.isAncillary())
357 .findFirst()
358 .orElse(Iterables.getFirst(allProviderIds, null));
359 }
360
361 /**
362 * Returns a Device, merging descriptions from multiple Providers.
363 *
364 * @param deviceId device identifier
365 * @return Device instance
366 */
367 private Device composeDevice(DeviceId deviceId) {
368
369 ProviderId primaryProviderId = getPrimaryProviderId(deviceId);
370 DeviceDescription primaryDeviceDescription =
371 deviceDescriptions.get(new DeviceKey(primaryProviderId, deviceId));
372
373 Type type = primaryDeviceDescription.type();
374 String manufacturer = primaryDeviceDescription.manufacturer();
375 String hwVersion = primaryDeviceDescription.hwVersion();
376 String swVersion = primaryDeviceDescription.swVersion();
377 String serialNumber = primaryDeviceDescription.serialNumber();
378 ChassisId chassisId = primaryDeviceDescription.chassisId();
379 DefaultAnnotations annotations = mergeAnnotations(deviceId);
380
381 return new DefaultDevice(primaryProviderId, deviceId, type, manufacturer,
382 hwVersion, swVersion, serialNumber,
383 chassisId, annotations);
384 }
385
386 private DeviceEvent purgeDeviceCache(DeviceId deviceId) {
387 Device removedDevice = devices.remove(deviceId);
388 if (removedDevice != null) {
389 getAllProviders(deviceId).forEach(p -> deviceDescriptions.remove(new DeviceKey(p, deviceId)));
390 return new DeviceEvent(DEVICE_REMOVED, removedDevice);
391 }
392 return null;
393 }
394
395 private boolean markOnline(DeviceId deviceId) {
396 return availableDevices.add(deviceId);
397 }
398
399 @Override
400 public DeviceEvent markOffline(DeviceId deviceId) {
401 availableDevices.remove(deviceId);
402 // set update listener will raise the event.
403 return null;
404 }
405
406 @Override
407 public List<DeviceEvent> updatePorts(ProviderId providerId,
408 DeviceId deviceId,
409 List<PortDescription> descriptions) {
410 NodeId master = mastershipService.getMasterFor(deviceId);
411 List<DeviceEvent> deviceEvents = null;
412 if (localNodeId.equals(master)) {
413 descriptions.forEach(description -> {
414 PortKey portKey = new PortKey(providerId, deviceId, description.portNumber());
415 portDescriptions.put(portKey, description);
416 });
417 deviceEvents = refreshDevicePortCache(providerId, deviceId, Optional.empty());
418 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800419 // Only forward for ConfigProvider
420 // Forwarding was added as a workaround for ONOS-490
HIGUCHI Yuta4ea4e422016-01-13 16:40:34 -0800421 if (!providerId.scheme().equals("cfg")) {
HIGUCHI Yuta89461772016-01-26 12:18:10 -0800422 return Collections.emptyList();
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800423 }
Madan Jampanifc8aced2015-08-27 11:06:12 -0700424 if (master == null) {
425 return Collections.emptyList();
426 }
427 PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, descriptions);
428 deviceEvents = Futures.getUnchecked(
429 clusterCommunicator.sendAndReceive(portInjectedEvent,
430 PORT_INJECTED,
431 SERIALIZER::encode,
432 SERIALIZER::decode,
433 master));
434 }
435 return deviceEvents == null ? Collections.emptyList() : deviceEvents;
436 }
437
438 private List<DeviceEvent> refreshDevicePortCache(ProviderId providerId,
439 DeviceId deviceId,
440 Optional<PortNumber> portNumber) {
441 Device device = devices.get(deviceId);
442 checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);
443 List<DeviceEvent> events = Lists.newArrayList();
444
445 Map<PortNumber, Port> ports = devicePorts.computeIfAbsent(deviceId, key -> Maps.newConcurrentMap());
446 List<PortDescription> descriptions = Lists.newArrayList();
447 portDescriptions.entrySet().forEach(e -> {
448 PortKey key = e.getKey();
449 PortDescription value = e.getValue();
450 if (key.deviceId().equals(deviceId) && key.providerId().equals(providerId)) {
451 if (portNumber.isPresent()) {
452 if (portNumber.get().equals(key.portNumber())) {
453 descriptions.add(value);
454 }
455 } else {
456 descriptions.add(value);
457 }
458 }
459 });
460
461 for (PortDescription description : descriptions) {
462 final PortNumber number = description.portNumber();
463 ports.compute(number, (k, existingPort) -> {
464 Port newPort = composePort(device, number);
465 if (existingPort == null) {
466 events.add(new DeviceEvent(PORT_ADDED, device, newPort));
467 } else {
468 if (existingPort.isEnabled() != newPort.isEnabled() ||
469 existingPort.type() != newPort.type() ||
470 existingPort.portSpeed() != newPort.portSpeed() ||
471 !AnnotationsUtil.isEqual(existingPort.annotations(), newPort.annotations())) {
472 events.add(new DeviceEvent(PORT_UPDATED, device, newPort));
473 }
474 }
475 return newPort;
476 });
477 }
478
479 return events;
480 }
481
482 /**
483 * Returns a Port, merging descriptions from multiple Providers.
484 *
485 * @param device device the port is on
486 * @param number port number
487 * @return Port instance
488 */
489 private Port composePort(Device device, PortNumber number) {
490
491 Map<ProviderId, PortDescription> descriptions = Maps.newHashMap();
492 portDescriptions.entrySet().forEach(entry -> {
493 PortKey portKey = entry.getKey();
494 if (portKey.deviceId().equals(device.id()) && portKey.portNumber().equals(number)) {
495 descriptions.put(portKey.providerId(), entry.getValue());
496 }
497 });
498 ProviderId primary = getPrimaryProviderId(device.id());
499 PortDescription primaryDescription = descriptions.get(primary);
500
501 // if no primary, assume not enabled
502 boolean isEnabled = false;
503 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
504 if (primaryDescription != null) {
505 isEnabled = primaryDescription.isEnabled();
506 annotations = merge(annotations, primaryDescription.annotations());
507 }
508 Port updated = null;
509 for (Entry<ProviderId, PortDescription> e : descriptions.entrySet()) {
510 if (e.getKey().equals(primary)) {
511 continue;
512 }
513 annotations = merge(annotations, e.getValue().annotations());
514 updated = buildTypedPort(device, number, isEnabled, e.getValue(), annotations);
515 }
516 if (primaryDescription == null) {
517 return updated == null ? new DefaultPort(device, number, false, annotations) : updated;
518 }
519 return updated == null
520 ? buildTypedPort(device, number, isEnabled, primaryDescription, annotations)
521 : updated;
522 }
523
524 private Port buildTypedPort(Device device, PortNumber number, boolean isEnabled,
525 PortDescription description, Annotations annotations) {
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -0800526 // FIXME this switch need to go away once all ports are done.
Madan Jampanifc8aced2015-08-27 11:06:12 -0700527 switch (description.type()) {
528 case OMS:
HIGUCHI Yuta95d83e82016-04-26 12:13:48 -0700529 if (description instanceof OmsPortDescription) {
530 // remove if-block once deprecation is complete
531 OmsPortDescription omsDesc = (OmsPortDescription) description;
532 return new OmsPort(device, number, isEnabled, omsDesc.minFrequency(),
533 omsDesc.maxFrequency(), omsDesc.grid(), annotations);
534 }
535 // same as default
536 return new DefaultPort(device, number, isEnabled, description.type(),
537 description.portSpeed(), annotations);
Madan Jampanifc8aced2015-08-27 11:06:12 -0700538 case OCH:
HIGUCHI Yuta34a3f692016-01-09 21:08:57 -0800539 if (description instanceof OchPortDescription) {
540 // remove if-block once Och deprecation is complete
541 OchPortDescription ochDesc = (OchPortDescription) description;
542 return new OchPort(device, number, isEnabled, ochDesc.signalType(),
543 ochDesc.isTunable(), ochDesc.lambda(), annotations);
544 }
545 return new DefaultPort(device, number, isEnabled, description.type(),
546 description.portSpeed(), annotations);
Madan Jampanifc8aced2015-08-27 11:06:12 -0700547 case ODUCLT:
HIGUCHI Yuta4c0ef6b2016-05-02 19:45:41 -0700548 if (description instanceof OduCltPortDescription) {
549 // remove if-block once deprecation is complete
550 OduCltPortDescription oduDesc = (OduCltPortDescription) description;
551 return new OduCltPort(device, number, isEnabled, oduDesc.signalType(), annotations);
552 }
553 // same as default
554 return new DefaultPort(device, number, isEnabled, description.type(),
555 description.portSpeed(), annotations);
Madan Jampanifc8aced2015-08-27 11:06:12 -0700556 default:
557 return new DefaultPort(device, number, isEnabled, description.type(),
558 description.portSpeed(), annotations);
559 }
560 }
561
562 @Override
563 public DeviceEvent updatePortStatus(ProviderId providerId,
564 DeviceId deviceId,
565 PortDescription portDescription) {
566 portDescriptions.put(new PortKey(providerId, deviceId, portDescription.portNumber()), portDescription);
567 List<DeviceEvent> events =
568 refreshDevicePortCache(providerId, deviceId, Optional.of(portDescription.portNumber()));
569 return Iterables.getFirst(events, null);
570 }
571
572 @Override
573 public List<Port> getPorts(DeviceId deviceId) {
574 return ImmutableList.copyOf(devicePorts.getOrDefault(deviceId, Maps.newHashMap()).values());
575 }
576
577 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700578 public Stream<PortDescription> getPortDescriptions(ProviderId pid,
579 DeviceId deviceId) {
580
581 return portDescriptions.entrySet().stream()
582 .filter(e -> e.getKey().providerId().equals(pid))
583 .map(Map.Entry::getValue);
584 }
585
586 @Override
Madan Jampanifc8aced2015-08-27 11:06:12 -0700587 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
588 return devicePorts.getOrDefault(deviceId, Maps.newHashMap()).get(portNumber);
589 }
590
591 @Override
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700592 public PortDescription getPortDescription(ProviderId pid,
593 DeviceId deviceId,
594 PortNumber portNumber) {
595 return portDescriptions.get(new PortKey(pid, deviceId, portNumber));
596 }
597
598 @Override
Madan Jampanifc8aced2015-08-27 11:06:12 -0700599 public DeviceEvent updatePortStatistics(ProviderId providerId,
600 DeviceId deviceId,
601 Collection<PortStatistics> newStatsCollection) {
602
603 Map<PortNumber, PortStatistics> prvStatsMap = devicePortStats.get(deviceId);
604 Map<PortNumber, PortStatistics> newStatsMap = Maps.newHashMap();
605 Map<PortNumber, PortStatistics> deltaStatsMap = Maps.newHashMap();
606
607 if (prvStatsMap != null) {
608 for (PortStatistics newStats : newStatsCollection) {
609 PortNumber port = PortNumber.portNumber(newStats.port());
610 PortStatistics prvStats = prvStatsMap.get(port);
611 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
612 PortStatistics deltaStats = builder.build();
613 if (prvStats != null) {
614 deltaStats = calcDeltaStats(deviceId, prvStats, newStats);
615 }
616 deltaStatsMap.put(port, deltaStats);
617 newStatsMap.put(port, newStats);
618 }
619 } else {
620 for (PortStatistics newStats : newStatsCollection) {
621 PortNumber port = PortNumber.portNumber(newStats.port());
622 newStatsMap.put(port, newStats);
623 }
624 }
625 devicePortDeltaStats.put(deviceId, deltaStatsMap);
626 devicePortStats.put(deviceId, newStatsMap);
627 // DeviceEvent returns null because of InternalPortStatsListener usage
628 return null;
629 }
630
631 /**
632 * Calculate delta statistics by subtracting previous from new statistics.
633 *
Madan Jampanif97edc12015-08-31 14:41:01 -0700634 * @param deviceId device indentifier
635 * @param prvStats previous port statistics
636 * @param newStats new port statistics
Madan Jampanifc8aced2015-08-27 11:06:12 -0700637 * @return PortStatistics
638 */
639 public PortStatistics calcDeltaStats(DeviceId deviceId, PortStatistics prvStats, PortStatistics newStats) {
640 // calculate time difference
641 long deltaStatsSec, deltaStatsNano;
642 if (newStats.durationNano() < prvStats.durationNano()) {
643 deltaStatsNano = newStats.durationNano() - prvStats.durationNano() + TimeUnit.SECONDS.toNanos(1);
644 deltaStatsSec = newStats.durationSec() - prvStats.durationSec() - 1L;
645 } else {
646 deltaStatsNano = newStats.durationNano() - prvStats.durationNano();
647 deltaStatsSec = newStats.durationSec() - prvStats.durationSec();
648 }
649 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
650 DefaultPortStatistics deltaStats = builder.setDeviceId(deviceId)
651 .setPort(newStats.port())
652 .setPacketsReceived(newStats.packetsReceived() - prvStats.packetsReceived())
653 .setPacketsSent(newStats.packetsSent() - prvStats.packetsSent())
654 .setBytesReceived(newStats.bytesReceived() - prvStats.bytesReceived())
655 .setBytesSent(newStats.bytesSent() - prvStats.bytesSent())
656 .setPacketsRxDropped(newStats.packetsRxDropped() - prvStats.packetsRxDropped())
657 .setPacketsTxDropped(newStats.packetsTxDropped() - prvStats.packetsTxDropped())
658 .setPacketsRxErrors(newStats.packetsRxErrors() - prvStats.packetsRxErrors())
659 .setPacketsTxErrors(newStats.packetsTxErrors() - prvStats.packetsTxErrors())
660 .setDurationSec(deltaStatsSec)
661 .setDurationNano(deltaStatsNano)
662 .build();
663 return deltaStats;
664 }
665
666 @Override
667 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
668 Map<PortNumber, PortStatistics> portStats = devicePortStats.get(deviceId);
669 if (portStats == null) {
670 return Collections.emptyList();
671 }
672 return ImmutableList.copyOf(portStats.values());
673 }
674
675 @Override
676 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
677 Map<PortNumber, PortStatistics> portStats = devicePortDeltaStats.get(deviceId);
678 if (portStats == null) {
679 return Collections.emptyList();
680 }
681 return ImmutableList.copyOf(portStats.values());
682 }
683
684 @Override
685 public boolean isAvailable(DeviceId deviceId) {
686 return availableDevices.contains(deviceId);
687 }
688
689 @Override
690 public Iterable<Device> getAvailableDevices() {
691 return Iterables.filter(Iterables.transform(availableDevices, devices::get), d -> d != null);
692 }
693
694 @Override
695 public DeviceEvent removeDevice(DeviceId deviceId) {
696 NodeId master = mastershipService.getMasterFor(deviceId);
697 // if there exist a master, forward
698 // if there is no master, try to become one and process
699 boolean relinquishAtEnd = false;
700 if (master == null) {
701 final MastershipRole myRole = mastershipService.getLocalRole(deviceId);
702 if (myRole != MastershipRole.NONE) {
703 relinquishAtEnd = true;
704 }
705 log.debug("Temporarily requesting role for {} to remove", deviceId);
706 MastershipRole role = Futures.getUnchecked(mastershipService.requestRoleFor(deviceId));
707 if (role == MastershipRole.MASTER) {
708 master = localNodeId;
709 }
710 }
711
712 if (!localNodeId.equals(master)) {
713 log.debug("{} has control of {}, forwarding remove request",
714 master, deviceId);
715
716 clusterCommunicator.unicast(deviceId, DEVICE_REMOVE_REQ, SERIALIZER::encode, master)
717 .whenComplete((r, e) -> {
718 if (e != null) {
719 log.error("Failed to forward {} remove request to its master", deviceId, e);
720 }
721 });
722 return null;
723 }
724
725 // I have control..
726 DeviceEvent event = null;
727 final DeviceKey deviceKey = new DeviceKey(getPrimaryProviderId(deviceId), deviceId);
728 DeviceDescription removedDeviceDescription =
729 deviceDescriptions.remove(deviceKey);
730 if (removedDeviceDescription != null) {
731 event = purgeDeviceCache(deviceId);
732 }
733
734 if (relinquishAtEnd) {
735 log.debug("Relinquishing temporary role acquired for {}", deviceId);
736 mastershipService.relinquishMastership(deviceId);
737 }
738 return event;
739 }
740
741 private DeviceEvent injectDevice(DeviceInjectedEvent event) {
742 return createOrUpdateDevice(event.providerId(), event.deviceId(), event.deviceDescription());
743 }
744
745 private List<DeviceEvent> injectPort(PortInjectedEvent event) {
746 return updatePorts(event.providerId(), event.deviceId(), event.portDescriptions());
747 }
748
749 private DefaultAnnotations mergeAnnotations(DeviceId deviceId) {
750 ProviderId primaryProviderId = getPrimaryProviderId(deviceId);
751 DeviceDescription primaryDeviceDescription =
752 deviceDescriptions.get(new DeviceKey(primaryProviderId, deviceId));
753 DefaultAnnotations annotations = DefaultAnnotations.builder().build();
754 annotations = merge(annotations, primaryDeviceDescription.annotations());
755 for (ProviderId providerId : getAllProviders(deviceId)) {
756 if (!providerId.equals(primaryProviderId)) {
757 annotations = merge(annotations,
758 deviceDescriptions.get(new DeviceKey(providerId, deviceId)).annotations());
759 }
760 }
761 return annotations;
762 }
763
764 private class InternalDeviceStatusTracker implements SetEventListener<DeviceId> {
765 @Override
766 public void event(SetEvent<DeviceId> event) {
767 final DeviceId deviceId = event.entry();
768 final Device device = devices.get(deviceId);
769 if (device != null) {
770 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, device));
771 } else {
772 pendingAvailableChangeUpdates.add(deviceId);
773 }
774 }
775 }
776
777 private class InternalDeviceChangeEventListener
778 implements EventuallyConsistentMapListener<DeviceKey, DeviceDescription> {
779 @Override
780 public void event(EventuallyConsistentMapEvent<DeviceKey, DeviceDescription> event) {
781 DeviceId deviceId = event.key().deviceId();
782 ProviderId providerId = event.key().providerId();
783 if (event.type() == PUT) {
784 notifyDelegate(refreshDeviceCache(providerId, deviceId));
785 if (pendingAvailableChangeUpdates.remove(deviceId)) {
786 notifyDelegate(new DeviceEvent(DEVICE_AVAILABILITY_CHANGED, devices.get(deviceId)));
787 }
788 } else if (event.type() == REMOVE) {
789 notifyDelegate(purgeDeviceCache(deviceId));
790 }
791 }
792 }
793
794 private class InternalPortChangeEventListener
795 implements EventuallyConsistentMapListener<PortKey, PortDescription> {
796 @Override
797 public void event(EventuallyConsistentMapEvent<PortKey, PortDescription> event) {
798 DeviceId deviceId = event.key().deviceId();
799 ProviderId providerId = event.key().providerId();
800 PortNumber portNumber = event.key().portNumber();
801 if (event.type() == PUT) {
802 if (devices.containsKey(deviceId)) {
803 List<DeviceEvent> events = refreshDevicePortCache(providerId, deviceId, Optional.of(portNumber));
804 for (DeviceEvent deviceEvent : events) {
805 notifyDelegate(deviceEvent);
806 }
807 }
808 } else if (event.type() == REMOVE) {
809 log.warn("Unexpected port removed event");
810 }
811 }
812 }
813
814 private class InternalPortStatsListener
815 implements EventuallyConsistentMapListener<DeviceId, Map<PortNumber, PortStatistics>> {
816 @Override
817 public void event(EventuallyConsistentMapEvent<DeviceId, Map<PortNumber, PortStatistics>> event) {
818 if (event.type() == PUT) {
819 Device device = devices.get(event.key());
820 if (device != null) {
821 delegate.notify(new DeviceEvent(PORT_STATS_UPDATED, device));
822 }
823 }
824 }
825 }
826}