Close device's source resolution on teardown
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / NetconfDevice.java
index 42ce7987f2b9fef0f37f4da3fa135b64381009d5..ca821798b1f724536fb3e46fa91329dc0becde13 100644 (file)
@@ -28,8 +28,10 @@ import java.util.Collection;
 import java.util.Collections;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
+import java.util.concurrent.CancellationException;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 import java.util.stream.Collectors;
@@ -58,8 +60,8 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.optional.rev19
 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.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
-import org.opendaylight.yangtools.rcf8528.data.util.EmptyMountPointContext;
 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
+import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcError;
@@ -115,6 +117,8 @@ public class NetconfDevice
     private final EventExecutor eventExecutor;
     private final NetconfNodeAugmentedOptional nodeOptional;
 
+    @GuardedBy("this")
+    private ListenableFuture<List<Object>> schemaFuturesList;
     @GuardedBy("this")
     private boolean connected = false;
 
@@ -140,18 +144,18 @@ public class NetconfDevice
         this.node = node;
         this.eventExecutor = eventExecutor;
         this.nodeOptional = nodeOptional;
-        this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
-        this.schemaRepository = schemaResourcesDTO.getSchemaRepository();
-        this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
+        schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
+        schemaRepository = schemaResourcesDTO.getSchemaRepository();
+        schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
         this.salFacade = salFacade;
-        this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
-        this.processingExecutor = requireNonNull(globalProcessingExecutor);
-        this.notificationHandler = new NotificationHandler(salFacade, id);
+        stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
+        processingExecutor = requireNonNull(globalProcessingExecutor);
+        notificationHandler = new NotificationHandler(salFacade, id);
     }
 
     @Override
-    public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
-                                  final NetconfDeviceCommunicator listener) {
+    public synchronized void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
+            final NetconfDeviceCommunicator listener) {
         // SchemaContext setup has to be performed in a dedicated thread since
         // we are in a netty thread in this method
         // Yang models are being downloaded in this method and it would cause a
@@ -177,18 +181,23 @@ public class NetconfDevice
         // Potentially acquire mount point list and interpret it
         final ListenableFuture<MountPointContext> futureContext = Futures.transformAsync(futureSchema,
             schemaContext -> createMountPointContext(schemaContext, baseSchema, listener), processingExecutor);
+        schemaFuturesList = Futures.allAsList(sourceResolverFuture, futureSchema, futureContext);
 
         Futures.addCallback(futureContext, new FutureCallback<MountPointContext>() {
             @Override
             public void onSuccess(final MountPointContext result) {
                 handleSalInitializationSuccess(result, remoteSessionCapabilities,
-                    getDeviceSpecificRpc(result, listener), listener);
+                        getDeviceSpecificRpc(result, listener, baseSchema), listener);
             }
 
             @Override
             public void onFailure(final Throwable cause) {
-                LOG.warn("{}: Unexpected error resolving device sources", id, cause);
+                if (cause instanceof CancellationException) {
+                    LOG.warn("{}: Device communicator was tear down since the schema setup started", id);
+                    return;
+                }
 
+                LOG.warn("{}: Unexpected error resolving device sources", id, cause);
                 // No more sources, fail or try to reconnect
                 if (cause instanceof EmptySchemaContextException) {
                     if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().getAllowed()) {
@@ -223,7 +232,7 @@ public class NetconfDevice
             @Override
             public void onSuccess(final DOMRpcResult domRpcResult) {
                 notificationHandler.addNotificationFilter(notification -> {
-                    if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getNodeType())) {
+                    if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getIdentifier().getNodeType())) {
                         LOG.info("{}: Schemas change detected, reconnecting", id);
                         // Only disconnect is enough,
                         // the reconnecting nature of the connector will take care of reconnecting
@@ -246,8 +255,6 @@ public class NetconfDevice
         return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
     }
 
-    @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
-            justification = "https://github.com/spotbugs/spotbugs/issues/811")
     private synchronized void handleSalInitializationSuccess(final MountPointContext result,
                                         final NetconfSessionPreferences remoteSessionCapabilities,
                                         final DOMRpcService deviceRpc,
@@ -255,14 +262,14 @@ public class NetconfDevice
         //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
         //since salFacade.onDeviceDisconnected was already called.
         if (connected) {
-            this.messageTransformer = new NetconfMessageTransformer(result, true,
+            messageTransformer = new NetconfMessageTransformer(result, true,
                 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
 
             // salFacade.onDeviceConnected has to be called before the notification handler is initialized
-            this.salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
-                    this.deviceActionFactory == null ? null : this.deviceActionFactory.createDeviceAction(
-                            this.messageTransformer, listener, result.getEffectiveModelContext()));
-            this.notificationHandler.onRemoteSchemaUp(this.messageTransformer);
+            salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
+                    deviceActionFactory == null ? null : deviceActionFactory.createDeviceAction(
+                            messageTransformer, listener, result.getEffectiveModelContext()));
+            notificationHandler.onRemoteSchemaUp(messageTransformer);
 
             LOG.info("{}: Netconf connector initialized successfully", id);
         } else {
@@ -270,8 +277,6 @@ public class NetconfDevice
         }
     }
 
-    @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
-            justification = "https://github.com/spotbugs/spotbugs/issues/811")
     private void handleSalInitializationFailure(final Throwable throwable,
                                                 final RemoteDeviceCommunicator<NetconfMessage> listener) {
         LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
@@ -295,8 +300,6 @@ public class NetconfDevice
         this.connected = connected;
     }
 
-    @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
-            justification = "https://github.com/spotbugs/spotbugs/issues/811")
     private ListenableFuture<EffectiveModelContext> assembleSchemaContext(final DeviceSources deviceSources,
             final NetconfSessionPreferences remoteSessionCapabilities) {
         LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
@@ -313,7 +316,7 @@ public class NetconfDevice
     private ListenableFuture<MountPointContext> createMountPointContext(final EffectiveModelContext schemaContext,
             final BaseSchema baseSchema, final NetconfDeviceCommunicator listener) {
         final MountPointContext emptyContext = new EmptyMountPointContext(schemaContext);
-        if (!schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isPresent()) {
+        if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
             return Futures.immediateFuture(emptyContext);
         }
 
@@ -333,7 +336,7 @@ public class NetconfDevice
         if (!errors.isEmpty()) {
             LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
         }
-        final NormalizedNode<?, ?> schemaMounts = rpcResult.getResult();
+        final NormalizedNode schemaMounts = rpcResult.getResult();
         if (schemaMounts == null) {
             LOG.debug("{}: device does not define any schema mounts", id);
             return emptyContext;
@@ -347,10 +350,14 @@ public class NetconfDevice
     }
 
     @Override
-    public void onRemoteSessionDown() {
+    public synchronized void onRemoteSessionDown() {
         setConnected(false);
+        if (schemaFuturesList != null && !schemaFuturesList.isDone()) {
+            if (!schemaFuturesList.cancel(true)) {
+                LOG.warn("The cleanup of Schema Futures for device {} was unsuccessful.", id);
+            }
+        }
         notificationHandler.onRemoteSchemaDown();
-
         salFacade.onDeviceDisconnected();
         sourceRegistrations.forEach(SchemaSourceRegistration::close);
         sourceRegistrations.clear();
@@ -373,9 +380,9 @@ public class NetconfDevice
     }
 
     protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
-            final RemoteDeviceCommunicator<NetconfMessage> listener) {
+            final RemoteDeviceCommunicator<NetconfMessage> listener, final BaseSchema schema) {
         return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
-            new NetconfMessageTransformer(result, true, baseSchemas.getBaseSchema()));
+            new NetconfMessageTransformer(result, true, schema));
     }
 
     /**
@@ -394,7 +401,7 @@ public class NetconfDevice
             this.schemaRegistry = requireNonNull(schemaRegistry);
             this.schemaRepository = requireNonNull(schemaRepository);
             this.schemaContextFactory = requireNonNull(schemaContextFactory);
-            this.stateSchemasResolver = requireNonNull(deviceSchemasResolver);
+            stateSchemasResolver = requireNonNull(deviceSchemasResolver);
         }
 
         public SchemaSourceRegistry getSchemaRegistry() {
@@ -442,7 +449,7 @@ public class NetconfDevice
         SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
             this.deviceSources = deviceSources;
             this.remoteSessionCapabilities = remoteSessionCapabilities;
-            this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
+            capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
 
             // If device supports notifications and does not contain necessary modules, add them automatically
             if (remoteSessionCapabilities.containsNonModuleCapability(
@@ -597,11 +604,11 @@ public class NetconfDevice
         private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
             // Required sources are all required and provided merged in DeviceSourcesResolver
             for (final QName qname : deviceSources.getRequiredSourcesQName()) {
-                if (!qname.getLocalName().equals(identifier.getName())) {
+                if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
                     continue;
                 }
 
-                if (identifier.getRevision().equals(qname.getRevision())) {
+                if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
                     return qname;
                 }
             }