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 8171764e03c2228798f5f8526057c126709f2630..ca821798b1f724536fb3e46fa91329dc0becde13 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.netconf.sal.connect.netconf;
 
 import static com.google.common.base.Preconditions.checkState;
 import static java.util.Objects.requireNonNull;
+import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
 
 import com.google.common.base.Predicates;
 import com.google.common.collect.Collections2;
@@ -22,12 +23,15 @@ import com.google.common.util.concurrent.SettableFuture;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import io.netty.util.concurrent.EventExecutor;
 import java.util.ArrayList;
+import java.util.Arrays;
 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;
@@ -35,6 +39,7 @@ import org.checkerframework.checker.lock.qual.GuardedBy;
 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
 import org.opendaylight.mdsal.dom.api.DOMRpcService;
 import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
@@ -45,6 +50,7 @@ import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabi
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
+import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseNetconfSchemas;
 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
@@ -54,12 +60,19 @@ 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.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.common.RpcError;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
+import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
@@ -81,8 +94,13 @@ public class NetconfDevice
             justification = "Needed for common logging of related classes")
     static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
 
+    private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
+        SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
+    private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
+        NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
+
     protected final RemoteDeviceId id;
-    protected final SchemaContextFactory schemaContextFactory;
+    protected final EffectiveModelContextFactory schemaContextFactory;
     protected final SchemaSourceRegistry schemaRegistry;
     protected final SchemaRepository schemaRepository;
 
@@ -94,47 +112,50 @@ public class NetconfDevice
     private final NetconfDeviceSchemasResolver stateSchemasResolver;
     private final NotificationHandler notificationHandler;
     private final boolean reconnectOnSchemasChange;
+    private final BaseNetconfSchemas baseSchemas;
     private final NetconfNode node;
     private final EventExecutor eventExecutor;
     private final NetconfNodeAugmentedOptional nodeOptional;
 
+    @GuardedBy("this")
+    private ListenableFuture<List<Object>> schemaFuturesList;
     @GuardedBy("this")
     private boolean connected = false;
 
     // Message transformer is constructed once the schemas are available
     private MessageTransformer<NetconfMessage> messageTransformer;
 
-    public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
-                         final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
-                         final ListeningExecutorService globalProcessingExecutor,
-                         final boolean reconnectOnSchemasChange) {
-        this(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null, null, null,
-                null);
+    public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
+            final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
+            final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
+        this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null,
+            null, null, null);
     }
 
-    public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
-            final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
+    public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
+            final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
             final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
             final DeviceActionFactory deviceActionFactory, final NetconfNode node, final EventExecutor eventExecutor,
             final NetconfNodeAugmentedOptional nodeOptional) {
+        this.baseSchemas = requireNonNull(baseSchemas);
         this.id = id;
         this.reconnectOnSchemasChange = reconnectOnSchemasChange;
         this.deviceActionFactory = deviceActionFactory;
         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
@@ -144,7 +165,7 @@ public class NetconfDevice
         LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
 
         final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
-        final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener,
+        final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
             new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
         final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
             new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
@@ -154,39 +175,40 @@ public class NetconfDevice
         }
 
         // Set up the SchemaContext for the device
-        final ListenableFuture<SchemaContext> futureSchema = Futures.transformAsync(sourceResolverFuture, schemas -> {
-            LOG.debug("{}: Resolved device sources to {}", id, schemas);
-            addProvidedSourcesToSchemaRegistry(schemas);
-            return new SchemaSetup(schemas, remoteSessionCapabilities).startResolution();
-        }, processingExecutor);
+        final ListenableFuture<EffectiveModelContext> futureSchema = Futures.transformAsync(sourceResolverFuture,
+            deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
 
         // Potentially acquire mount point list and interpret it
-        final ListenableFuture<MountPointContext> futureContext = Futures.transform(futureSchema, schemaContext -> {
-            // FIXME: check if there is RFC8528 schema available
-            return new EmptyMountPointContext(schemaContext);
-        }, processingExecutor);
+        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().isAllowed()) {
+                    if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().getAllowed()) {
                         eventExecutor.schedule(() -> {
                             LOG.warn("Reconnection is allowed! This can lead to unexpected errors at runtime.");
                             LOG.warn("{} : No more sources for schema context.", id);
                             LOG.info("{} : Try to remount device.", id);
                             onRemoteSessionDown();
                             salFacade.onDeviceReconnected(remoteSessionCapabilities, node);
-                        }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime(), TimeUnit.MILLISECONDS);
+                        }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime().toJava(),
+                            TimeUnit.MILLISECONDS);
                         return;
                     }
                 }
@@ -203,14 +225,14 @@ public class NetconfDevice
         // Perhaps add a default schema context to support create-subscription if the model was not provided
         // (same as what we do for base netconf operations in transformer)
         final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
-                NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_PATH,
+                NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
 
         Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
             @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
@@ -233,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,
@@ -242,16 +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) {
-            final BaseSchema baseSchema =
-                remoteSessionCapabilities.isNotificationsSupported()
-                        ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
-            this.messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
+            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.getSchemaContext()));
-            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 {
@@ -259,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);
@@ -284,22 +300,64 @@ public class NetconfDevice
         this.connected = connected;
     }
 
-    @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
-            justification = "https://github.com/spotbugs/spotbugs/issues/811")
-    private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
+    private ListenableFuture<EffectiveModelContext> assembleSchemaContext(final DeviceSources deviceSources,
+            final NetconfSessionPreferences remoteSessionCapabilities) {
+        LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
         final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
         for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
             sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
-                    PotentialSchemaSource.create(
-                            sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
+                PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class,
+                    PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
         }
+
+        return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
+    }
+
+    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).isEmpty()) {
+            return Futures.immediateFuture(emptyContext);
+        }
+
+        // Create a temporary RPC invoker and acquire the mount point tree
+        LOG.debug("{}: Acquiring available mount points", id);
+        final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
+            new NetconfMessageTransformer(emptyContext, false, baseSchema));
+
+        return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
+            Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
+                .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
+                .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
+    }
+
+    private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
+        final Collection<? extends RpcError> errors = rpcResult.getErrors();
+        if (!errors.isEmpty()) {
+            LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
+        }
+        final NormalizedNode schemaMounts = rpcResult.getResult();
+        if (schemaMounts == null) {
+            LOG.debug("{}: device does not define any schema mounts", id);
+            return emptyContext;
+        }
+        if (!(schemaMounts instanceof ContainerNode)) {
+            LOG.warn("{}: ignoring non-container schema mounts {}", id, schemaMounts);
+            return emptyContext;
+        }
+
+        return DeviceMountPointContext.create(emptyContext, (ContainerNode) schemaMounts);
     }
 
     @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();
@@ -317,13 +375,14 @@ public class NetconfDevice
         notificationHandler.handleNotification(notification);
     }
 
-    private static BaseSchema resolveBaseSchema(final boolean notificationSupport) {
-        return notificationSupport ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
+    private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
+        return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
     }
 
     protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
-            final RemoteDeviceCommunicator<NetconfMessage> listener) {
-        return new NetconfDeviceRpc(result.getSchemaContext(), listener, new NetconfMessageTransformer(result, true));
+            final RemoteDeviceCommunicator<NetconfMessage> listener, final BaseSchema schema) {
+        return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
+            new NetconfMessageTransformer(result, true, schema));
     }
 
     /**
@@ -332,17 +391,17 @@ public class NetconfDevice
     public static class SchemaResourcesDTO {
         private final SchemaSourceRegistry schemaRegistry;
         private final SchemaRepository schemaRepository;
-        private final SchemaContextFactory schemaContextFactory;
+        private final EffectiveModelContextFactory schemaContextFactory;
         private final NetconfDeviceSchemasResolver stateSchemasResolver;
 
         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
                                   final SchemaRepository schemaRepository,
-                                  final SchemaContextFactory schemaContextFactory,
+                                  final EffectiveModelContextFactory schemaContextFactory,
                                   final NetconfDeviceSchemasResolver deviceSchemasResolver) {
             this.schemaRegistry = requireNonNull(schemaRegistry);
             this.schemaRepository = requireNonNull(schemaRepository);
             this.schemaContextFactory = requireNonNull(schemaContextFactory);
-            this.stateSchemasResolver = requireNonNull(deviceSchemasResolver);
+            stateSchemasResolver = requireNonNull(deviceSchemasResolver);
         }
 
         public SchemaSourceRegistry getSchemaRegistry() {
@@ -353,7 +412,7 @@ public class NetconfDevice
             return schemaRepository;
         }
 
-        public SchemaContextFactory getSchemaContextFactory() {
+        public EffectiveModelContextFactory getSchemaContextFactory() {
             return schemaContextFactory;
         }
 
@@ -378,8 +437,8 @@ public class NetconfDevice
     /**
      * Schema builder that tries to build schema context from provided sources or biggest subset of it.
      */
-    private final class SchemaSetup implements FutureCallback<SchemaContext> {
-        private final SettableFuture<SchemaContext> resultFuture = SettableFuture.create();
+    private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
+        private final SettableFuture<EffectiveModelContext> resultFuture = SettableFuture.create();
 
         private final DeviceSources deviceSources;
         private final NetconfSessionPreferences remoteSessionCapabilities;
@@ -390,7 +449,20 @@ 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(
+                    XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0)) {
+                deviceSources.getRequiredSourcesQName().addAll(
+                        Arrays.asList(
+                                org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
+                                        .$YangModuleInfoImpl.getInstance().getName(),
+                                org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
+                                        .$YangModuleInfoImpl.getInstance().getName()
+                        )
+                );
+            }
 
             requiredSources = deviceSources.getRequiredSources();
             final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
@@ -400,13 +472,13 @@ public class NetconfDevice
             requiredSources.removeAll(missingSources);
         }
 
-        ListenableFuture<SchemaContext> startResolution() {
+        ListenableFuture<EffectiveModelContext> startResolution() {
             trySetupSchema();
             return resultFuture;
         }
 
         @Override
-        public void onSuccess(final SchemaContext result) {
+        public void onSuccess(final EffectiveModelContext result) {
             LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
 
             final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
@@ -448,7 +520,7 @@ public class NetconfDevice
             if (!requiredSources.isEmpty()) {
                 // Initiate async resolution, drive it back based on the result
                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
-                Futures.addCallback(schemaContextFactory.createSchemaContext(requiredSources), this,
+                Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
                     MoreExecutors.directExecutor());
             } else {
                 LOG.debug("{}: no more sources for schema context", id);
@@ -532,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;
                 }
             }