Bump upstream dependencies to K-SR2
[transportpce.git] / networkmodel / src / main / java / org / opendaylight / transportpce / networkmodel / NetConfTopologyListener.java
index dfc90dd3de49f5f83f83cca751fe52cccbf0a5db..ce15d3377f810b3688b34b49e2cd8eb12b57f8ee 100644 (file)
@@ -9,12 +9,13 @@ package org.opendaylight.transportpce.networkmodel;
 
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.util.concurrent.ListenableFuture;
+import java.util.ArrayList;
 import java.util.Collection;
+import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutionException;
-import javax.annotation.Nonnull;
 import org.opendaylight.mdsal.binding.api.DataBroker;
 import org.opendaylight.mdsal.binding.api.DataObjectModification;
 import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
@@ -36,9 +37,9 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification.
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.Netconf;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.streams.Stream;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus.ConnectionStatus;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240118.ConnectionOper.ConnectionStatus;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240118.connection.oper.available.capabilities.AvailableCapability;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev221225.NetconfNode;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcResult;
@@ -55,8 +56,11 @@ public class NetConfTopologyListener implements DataTreeChangeListener<Node> {
     private final Map<String, NodeRegistration> registrations;
     private final PortMapping portMapping;
 
-    public NetConfTopologyListener(final NetworkModelService networkModelService, final DataBroker dataBroker,
-             DeviceTransactionManager deviceTransactionManager, PortMapping portMapping) {
+    public NetConfTopologyListener(
+            final NetworkModelService networkModelService,
+            final DataBroker dataBroker,
+            DeviceTransactionManager deviceTransactionManager,
+            PortMapping portMapping) {
         this.networkModelService = networkModelService;
         this.dataBroker = dataBroker;
         this.deviceTransactionManager = deviceTransactionManager;
@@ -64,7 +68,8 @@ public class NetConfTopologyListener implements DataTreeChangeListener<Node> {
         this.portMapping = portMapping;
     }
 
-    public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<Node>> changes) {
+    @Override
+    public void onDataTreeChanged(Collection<DataTreeModification<Node>> changes) {
         LOG.info("onDataTreeChanged - {}", this.getClass().getSimpleName());
         for (DataTreeModification<Node> change : changes) {
             DataObjectModification<Node> rootNode = change.getRootNode();
@@ -75,31 +80,32 @@ public class NetConfTopologyListener implements DataTreeChangeListener<Node> {
             NetconfNode netconfNodeBefore = rootNode.getDataBefore().augmentation(NetconfNode.class);
             switch (rootNode.getModificationType()) {
                 case DELETE:
-                    this.networkModelService.deleteOpenRoadmnode(nodeId);
-                    onDeviceDisConnected(nodeId);
-                    LOG.info("Device {} correctly disconnected from controller", nodeId);
+                    if (this.networkModelService.deleteOpenRoadmnode(nodeId)) {
+                        onDeviceDisConnected(nodeId);
+                        LOG.info("Device {} correctly disconnected from controller", nodeId);
+                    }
                     break;
                 case WRITE:
                     NetconfNode netconfNodeAfter = rootNode.getDataAfter().augmentation(NetconfNode.class);
                     if (ConnectionStatus.Connecting.equals(netconfNodeBefore.getConnectionStatus())
-                        && ConnectionStatus.Connected.equals(netconfNodeAfter.getConnectionStatus())) {
+                            && ConnectionStatus.Connected.equals(netconfNodeAfter.getConnectionStatus())) {
                         LOG.info("Connecting Node: {}", nodeId);
-                        Optional<AvailableCapability> deviceCapabilityOpt = netconfNodeAfter
-                            .getAvailableCapabilities().getAvailableCapability().stream()
-                            .filter(cp -> cp.getCapability().contains(StringConstants.OPENROADM_DEVICE_MODEL_NAME))
-                            .sorted((c1, c2) -> c2.getCapability().compareTo(c1.getCapability()))
-                            .findFirst();
+                        Optional<AvailableCapability> deviceCapabilityOpt =
+                            netconfNodeAfter.getAvailableCapabilities().getAvailableCapability().stream()
+                                .filter(cp -> cp.getCapability().contains(StringConstants.OPENROADM_DEVICE_MODEL_NAME))
+                                .sorted((c1, c2) -> c2.getCapability().compareTo(c1.getCapability()))
+                                .findFirst();
                         if (deviceCapabilityOpt.isEmpty()) {
                             LOG.error("Unable to get openroadm-device-capability");
                             return;
                         }
                         this.networkModelService
-                            .createOpenRoadmNode(nodeId, deviceCapabilityOpt.get().getCapability());
-                        onDeviceConnected(nodeId,deviceCapabilityOpt.get().getCapability());
+                            .createOpenRoadmNode(nodeId, deviceCapabilityOpt.orElseThrow().getCapability());
+                        onDeviceConnected(nodeId, deviceCapabilityOpt.orElseThrow().getCapability());
                         LOG.info("Device {} correctly connected to controller", nodeId);
                     }
                     if (ConnectionStatus.Connected.equals(netconfNodeBefore.getConnectionStatus())
-                        && ConnectionStatus.Connecting.equals(netconfNodeAfter.getConnectionStatus())) {
+                            && ConnectionStatus.Connecting.equals(netconfNodeAfter.getConnectionStatus())) {
                         LOG.warn("Node: {} is being disconnected", nodeId);
                     }
                     break;
@@ -113,60 +119,60 @@ public class NetConfTopologyListener implements DataTreeChangeListener<Node> {
     private void onDeviceConnected(final String nodeId, String openRoadmVersion) {
         LOG.info("onDeviceConnected: {}", nodeId);
         Optional<MountPoint> mountPointOpt = this.deviceTransactionManager.getDeviceMountPoint(nodeId);
-        MountPoint mountPoint;
-        if (mountPointOpt.isPresent()) {
-            mountPoint = mountPointOpt.get();
-        } else {
+        if (mountPointOpt.isEmpty()) {
             LOG.error("Failed to get mount point for node {}", nodeId);
             return;
         }
+        MountPoint mountPoint = mountPointOpt.orElseThrow();
         final Optional<NotificationService> notificationService = mountPoint.getService(NotificationService.class);
-        if (!notificationService.isPresent()) {
+        if (notificationService.isEmpty()) {
             LOG.error(RPC_SERVICE_FAILED, nodeId);
             return;
         }
-        NodeRegistration nodeRegistration = new NodeRegistration(nodeId, openRoadmVersion,
-            notificationService.get(), this.dataBroker, this.portMapping);
+        NodeRegistration nodeRegistration =
+            new NodeRegistration(
+                nodeId, openRoadmVersion, notificationService.orElseThrow(), this.dataBroker, this.portMapping);
         nodeRegistration.registerListeners();
         registrations.put(nodeId, nodeRegistration);
-        String streamName = getSupportedStream(nodeId);
-        LOG.info("Device is supporting notification stream {}",streamName);
-        subscribeStream(mountPoint, streamName, nodeId);
+
+        subscribeStream(mountPoint, nodeId);
     }
 
     private void onDeviceDisConnected(final String nodeId) {
         LOG.info("onDeviceDisConnected: {}", nodeId);
-        NodeRegistration nodeRegistration = this.registrations.remove(nodeId);
-        nodeRegistration.unregisterListeners();
+        this.registrations.remove(nodeId).unregisterListeners();
     }
 
-    private boolean subscribeStream(MountPoint mountPoint, String streamName, String nodeId) {
+    private boolean subscribeStream(MountPoint mountPoint, String nodeId) {
         final Optional<RpcConsumerRegistry> service = mountPoint.getService(RpcConsumerRegistry.class);
-        if (!service.isPresent()) {
+        if (service.isEmpty()) {
             return false;
         }
-        final NotificationsService rpcService = service.get().getRpcService(NotificationsService.class);
+        final NotificationsService rpcService = service.orElseThrow().getRpcService(NotificationsService.class);
         if (rpcService == null) {
             LOG.error(RPC_SERVICE_FAILED, nodeId);
             return false;
         }
-        final CreateSubscriptionInputBuilder createSubscriptionInputBuilder = new CreateSubscriptionInputBuilder()
-            .setStream(new StreamNameType(streamName));
-        LOG.info("Triggering notification stream {} for node {}", streamName, nodeId);
-        ListenableFuture<RpcResult<CreateSubscriptionOutput>> subscription = rpcService
-            .createSubscription(createSubscriptionInputBuilder.build());
-        try {
-            subscription.get();
-        } catch (InterruptedException | ExecutionException e) {
-            LOG.error("Error during subscription to stream {}", streamName, e);
+        // Set the default stream as OPENROADM
+        for (String streamName : getSupportedStream(nodeId)) {
+            LOG.info("Triggering notification stream {} for node {}", streamName, nodeId);
+            ListenableFuture<RpcResult<CreateSubscriptionOutput>> subscription =
+                rpcService.createSubscription(
+                    new CreateSubscriptionInputBuilder().setStream(new StreamNameType(streamName)).build());
+            if (checkSupportedStream(streamName, subscription)) {
+                return true;
+            }
         }
-        return true;
+        return false;
     }
 
     @VisibleForTesting
-    public NetConfTopologyListener(final NetworkModelService networkModelService, final DataBroker dataBroker,
-        DeviceTransactionManager deviceTransactionManager, PortMapping portMapping,
-        Map<String, NodeRegistration> registrations) {
+    public NetConfTopologyListener(
+            final NetworkModelService networkModelService,
+            final DataBroker dataBroker,
+            DeviceTransactionManager deviceTransactionManager,
+            PortMapping portMapping,
+            Map<String, NodeRegistration> registrations) {
         this.networkModelService = networkModelService;
         this.dataBroker = dataBroker;
         this.deviceTransactionManager = deviceTransactionManager;
@@ -174,21 +180,45 @@ public class NetConfTopologyListener implements DataTreeChangeListener<Node> {
         this.registrations = registrations;
     }
 
-    private String getSupportedStream(String nodeId) {
+    private boolean checkSupportedStream(
+            String streamName,
+            ListenableFuture<RpcResult<CreateSubscriptionOutput>> subscription) {
+        boolean subscriptionSuccessful = false;
+        try {
+            // Using if condition does not work, since we need to handle exceptions
+            subscriptionSuccessful = subscription.get().isSuccessful();
+            LOG.info("{} subscription is {}", streamName, subscriptionSuccessful);
+        } catch (InterruptedException | ExecutionException e) {
+            LOG.error("Error during subscription to stream {}", streamName, e);
+        }
+        return subscriptionSuccessful;
+    }
+
+    private List<String> getSupportedStream(String nodeId) {
         InstanceIdentifier<Streams> streamsIID = InstanceIdentifier.create(Netconf.class).child(Streams.class);
         Optional<Streams> ordmInfoObject =
                 deviceTransactionManager.getDataFromDevice(nodeId, LogicalDatastoreType.OPERATIONAL, streamsIID,
                         Timeouts.DEVICE_READ_TIMEOUT, Timeouts.DEVICE_READ_TIMEOUT_UNIT);
-        if (ordmInfoObject == null || ordmInfoObject.isEmpty() || ordmInfoObject.get().getStream().isEmpty()) {
+        if (ordmInfoObject == null || ordmInfoObject.isEmpty() || ordmInfoObject.orElseThrow().getStream().isEmpty()) {
             LOG.error("List of streams supports by device is not present");
-            return "NETCONF";
+            return List.of("OPENROADM","NETCONF");
         }
-        for (Stream strm : ordmInfoObject.get().getStream().values()) {
+        List<String> streams = new ArrayList<>();
+        List<String> netconfStreams = new ArrayList<>();
+        for (Stream strm : ordmInfoObject.orElseThrow().getStream().values()) {
             LOG.debug("Streams are {}", strm);
             if ("OPENROADM".equalsIgnoreCase(strm.getName().getValue())) {
-                return strm.getName().getValue();
+                streams.add(strm.getName().getValue());
+            } else if ("NETCONF".equalsIgnoreCase(strm.getName().getValue())) {
+                netconfStreams.add(strm.getName().getValue());
             }
         }
-        return "NETCONF";
+        // If OpenROADM streams are not supported, try NETCONF streams subscription
+        streams.addAll(netconfStreams);
+        return
+            streams.isEmpty()
+                ? List.of("OPENROADM","NETCONF")
+                : streams;
     }
+
 }