Propagate MountPointContext to NetconfMessageTransformer
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / NetconfDevice.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netconf.sal.connect.netconf;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.Predicates;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Sets;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.ListeningExecutorService;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import io.netty.util.concurrent.EventExecutor;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.Optional;
29 import java.util.Set;
30 import java.util.concurrent.Callable;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.TimeUnit;
33 import java.util.stream.Collectors;
34 import org.checkerframework.checker.lock.qual.GuardedBy;
35 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
36 import org.opendaylight.mdsal.dom.api.DOMRpcService;
37 import org.opendaylight.netconf.api.NetconfMessage;
38 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
39 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
40 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
41 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
42 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
43 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
44 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
45 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
47 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
48 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
49 import org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
50 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
51 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
52 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
53 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
54 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.optional.rev190614.NetconfNodeAugmentedOptional;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
60 import org.opendaylight.yangtools.rcf8528.data.util.EmptyMountPointContext;
61 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
62 import org.opendaylight.yangtools.yang.common.QName;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
65 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
66 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
67 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
68 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
69 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
70 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
71 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
72 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
73 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
74 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77
78 /**
79  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
80  */
81 public class NetconfDevice
82         implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
83
84     private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
85
86     protected final RemoteDeviceId id;
87     protected final SchemaContextFactory schemaContextFactory;
88     protected final SchemaSourceRegistry schemaRegistry;
89     protected final SchemaRepository schemaRepository;
90
91     protected final List<SchemaSourceRegistration<?>> sourceRegistrations = new ArrayList<>();
92
93     private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
94     private final ListeningExecutorService processingExecutor;
95     private final DeviceActionFactory deviceActionFactory;
96     private final NetconfDeviceSchemasResolver stateSchemasResolver;
97     private final NotificationHandler notificationHandler;
98     private final boolean reconnectOnSchemasChange;
99     private final NetconfNode node;
100     private final EventExecutor eventExecutor;
101     private final NetconfNodeAugmentedOptional nodeOptional;
102
103     @GuardedBy("this")
104     private boolean connected = false;
105
106     // Message transformer is constructed once the schemas are available
107     private MessageTransformer<NetconfMessage> messageTransformer;
108
109     /**
110      * Create rpc implementation capable of handling RPC for monitoring and notifications
111      * even before the schemas of remote device are downloaded.
112      */
113     static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener,
114                                                     final boolean notificationSupport) {
115         final BaseSchema baseSchema = resolveBaseSchema(notificationSupport);
116
117         return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener,
118                 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
119     }
120
121     private static BaseSchema resolveBaseSchema(final boolean notificationSupport) {
122         return notificationSupport ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
123     }
124
125     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
126                          final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
127                          final ListeningExecutorService globalProcessingExecutor,
128                          final boolean reconnectOnSchemasChange) {
129         this(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null, null, null,
130                 null);
131     }
132
133     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
134             final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
135             final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
136             final DeviceActionFactory deviceActionFactory, final NetconfNode node, final EventExecutor eventExecutor,
137             final NetconfNodeAugmentedOptional nodeOptional) {
138         this.id = id;
139         this.reconnectOnSchemasChange = reconnectOnSchemasChange;
140         this.deviceActionFactory = deviceActionFactory;
141         this.node = node;
142         this.eventExecutor = eventExecutor;
143         this.nodeOptional = nodeOptional;
144         this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
145         this.schemaRepository = schemaResourcesDTO.getSchemaRepository();
146         this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
147         this.salFacade = salFacade;
148         this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
149         this.processingExecutor = requireNonNull(globalProcessingExecutor);
150         this.notificationHandler = new NotificationHandler(salFacade, id);
151     }
152
153     @Override
154     public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
155                                   final NetconfDeviceCommunicator listener) {
156         // SchemaContext setup has to be performed in a dedicated thread since
157         // we are in a netty thread in this method
158         // Yang models are being downloaded in this method and it would cause a
159         // deadlock if we used the netty thread
160         // http://netty.io/wiki/thread-model.html
161         setConnected(true);
162         LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
163
164         final NetconfDeviceRpc initRpc =
165                 getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
166         final DeviceSourcesResolver task =
167                 new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc,
168                         resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()).getSchemaContext());
169         final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
170
171         if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
172             registerToBaseNetconfStream(initRpc, listener);
173         }
174
175         final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
176             @Override
177             public void onSuccess(final DeviceSources result) {
178                 addProvidedSourcesToSchemaRegistry(result);
179                 setUpSchema(result);
180             }
181
182             private void setUpSchema(final DeviceSources result) {
183                 processingExecutor.submit(new SchemaSetup(result, remoteSessionCapabilities, listener));
184             }
185
186             @Override
187             public void onFailure(final Throwable throwable) {
188                 LOG.warn("{}: Unexpected error resolving device sources", id, throwable);
189                 handleSalInitializationFailure(throwable, listener);
190             }
191         };
192
193         Futures.addCallback(sourceResolverFuture, resolvedSourceCallback, MoreExecutors.directExecutor());
194     }
195
196     private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
197                                              final NetconfDeviceCommunicator listener) {
198         // TODO check whether the model describing create subscription is present in schema
199         // Perhaps add a default schema context to support create-subscription if the model was not provided
200         // (same as what we do for base netconf operations in transformer)
201         final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
202                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_PATH,
203                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
204
205         Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
206             @Override
207             public void onSuccess(final DOMRpcResult domRpcResult) {
208                 notificationHandler.addNotificationFilter(notification -> {
209                     if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getNodeType())) {
210                         LOG.info("{}: Schemas change detected, reconnecting", id);
211                         // Only disconnect is enough,
212                         // the reconnecting nature of the connector will take care of reconnecting
213                         listener.disconnect();
214                         return Optional.empty();
215                     }
216                     return Optional.of(notification);
217                 });
218             }
219
220             @Override
221             public void onFailure(final Throwable throwable) {
222                 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
223                         throwable);
224             }
225         }, MoreExecutors.directExecutor());
226     }
227
228     private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
229         return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
230     }
231
232     private synchronized void handleSalInitializationSuccess(final MountPointContext result,
233                                         final NetconfSessionPreferences remoteSessionCapabilities,
234                                         final DOMRpcService deviceRpc,
235                                         final RemoteDeviceCommunicator<NetconfMessage> listener) {
236         //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
237         //since salFacade.onDeviceDisconnected was already called.
238         if (connected) {
239             final BaseSchema baseSchema =
240                 remoteSessionCapabilities.isNotificationsSupported()
241                         ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
242             this.messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
243
244             // salFacade.onDeviceConnected has to be called before the notification handler is initialized
245             this.salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
246                     this.deviceActionFactory == null ? null : this.deviceActionFactory.createDeviceAction(
247                             this.messageTransformer, listener, result.getSchemaContext()));
248             this.notificationHandler.onRemoteSchemaUp(this.messageTransformer);
249
250             LOG.info("{}: Netconf connector initialized successfully", id);
251         } else {
252             LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
253         }
254     }
255
256     private void handleSalInitializationFailure(final Throwable throwable,
257                                                 final RemoteDeviceCommunicator<NetconfMessage> listener) {
258         LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
259         listener.close();
260         onRemoteSessionDown();
261         resetMessageTransformer();
262     }
263
264     /**
265      * Set the transformer to null as is in initial state.
266      */
267     private void resetMessageTransformer() {
268         updateTransformer(null);
269     }
270
271     private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
272         messageTransformer = transformer;
273     }
274
275     private synchronized void setConnected(final boolean connected) {
276         this.connected = connected;
277     }
278
279     private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
280         final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
281         for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
282             sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
283                     PotentialSchemaSource.create(
284                             sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
285         }
286     }
287
288     @Override
289     public void onRemoteSessionDown() {
290         setConnected(false);
291         notificationHandler.onRemoteSchemaDown();
292
293         salFacade.onDeviceDisconnected();
294         sourceRegistrations.forEach(SchemaSourceRegistration::close);
295         sourceRegistrations.clear();
296         resetMessageTransformer();
297     }
298
299     @Override
300     public void onRemoteSessionFailed(final Throwable throwable) {
301         setConnected(false);
302         salFacade.onDeviceFailed(throwable);
303     }
304
305     @Override
306     public void onNotification(final NetconfMessage notification) {
307         notificationHandler.handleNotification(notification);
308     }
309
310     /**
311      * Just a transfer object containing schema related dependencies. Injected in constructor.
312      */
313     public static class SchemaResourcesDTO {
314         private final SchemaSourceRegistry schemaRegistry;
315         private final SchemaRepository schemaRepository;
316         private final SchemaContextFactory schemaContextFactory;
317         private final NetconfDeviceSchemasResolver stateSchemasResolver;
318
319         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
320                                   final SchemaRepository schemaRepository,
321                                   final SchemaContextFactory schemaContextFactory,
322                                   final NetconfDeviceSchemasResolver deviceSchemasResolver) {
323             this.schemaRegistry = requireNonNull(schemaRegistry);
324             this.schemaRepository = requireNonNull(schemaRepository);
325             this.schemaContextFactory = requireNonNull(schemaContextFactory);
326             this.stateSchemasResolver = requireNonNull(deviceSchemasResolver);
327         }
328
329         public SchemaSourceRegistry getSchemaRegistry() {
330             return schemaRegistry;
331         }
332
333         public SchemaRepository getSchemaRepository() {
334             return schemaRepository;
335         }
336
337         public SchemaContextFactory getSchemaContextFactory() {
338             return schemaContextFactory;
339         }
340
341         public NetconfDeviceSchemasResolver getStateSchemasResolver() {
342             return stateSchemasResolver;
343         }
344     }
345
346     /**
347      * Schema building callable.
348      */
349     private static class DeviceSourcesResolver implements Callable<DeviceSources> {
350
351         private final NetconfDeviceRpc deviceRpc;
352         private final NetconfSessionPreferences remoteSessionCapabilities;
353         private final RemoteDeviceId id;
354         private final NetconfDeviceSchemasResolver stateSchemasResolver;
355         private final SchemaContext schemaContext;
356
357         DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc,
358                               final NetconfSessionPreferences remoteSessionCapabilities,
359                               final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver,
360                               final SchemaContext schemaContext) {
361             this.deviceRpc = deviceRpc;
362             this.remoteSessionCapabilities = remoteSessionCapabilities;
363             this.id = id;
364             this.stateSchemasResolver = stateSchemasResolver;
365             this.schemaContext = schemaContext;
366         }
367
368         DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
369                                      final NetconfDeviceSchemasResolver stateSchemasResolver,
370                                      final NetconfDeviceRpc rpcForMonitoring, final SchemaContext schemaCtx) {
371             this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver, schemaCtx);
372         }
373
374         @Override
375         public DeviceSources call() {
376             final NetconfDeviceSchemas availableSchemas =
377                     stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id, schemaContext);
378             LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id,
379                     availableSchemas.getAvailableYangSchemasQNames());
380
381             final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
382             final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
383
384             final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
385             if (!requiredSourcesNotProvided.isEmpty()) {
386                 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities,"
387                         + " required but not provided: {}", id, requiredSourcesNotProvided);
388                 LOG.warn("{}: Attempting to build schema context from required sources", id);
389             }
390
391             // Here all the sources reported in netconf monitoring are merged with those reported in hello.
392             // It is necessary to perform this since submodules are not mentioned in hello but still required.
393             // This clashes with the option of a user to specify supported yang models manually in configuration
394             // for netconf-connector and as a result one is not able to fully override yang models of a device.
395             // It is only possible to add additional models.
396             final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
397             if (!providedSourcesNotRequired.isEmpty()) {
398                 LOG.warn("{}: Netconf device provides additional yang models not reported in "
399                         + "hello message capabilities: {}", id, providedSourcesNotRequired);
400                 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
401                 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
402                 requiredSources.addAll(providedSourcesNotRequired);
403             }
404
405             final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
406             if (availableSchemas instanceof LibraryModulesSchemas) {
407                 sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
408                         ((LibraryModulesSchemas) availableSchemas).getAvailableModels());
409             } else {
410                 sourceProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
411             }
412
413             return new DeviceSources(requiredSources, providedSources, sourceProvider);
414         }
415     }
416
417     /**
418      * Contains RequiredSources - sources from capabilities.
419      */
420     private static final class DeviceSources {
421         private final Set<QName> requiredSources;
422         private final Set<QName> providedSources;
423         private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
424
425         DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
426                              final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
427             this.requiredSources = requiredSources;
428             this.providedSources = providedSources;
429             this.sourceProvider = sourceProvider;
430         }
431
432         public Set<QName> getRequiredSourcesQName() {
433             return requiredSources;
434         }
435
436         public Set<QName> getProvidedSourcesQName() {
437             return providedSources;
438         }
439
440         public Collection<SourceIdentifier> getRequiredSources() {
441             return Collections2.transform(requiredSources, DeviceSources::toSourceId);
442         }
443
444         public Collection<SourceIdentifier> getProvidedSources() {
445             return Collections2.transform(providedSources, DeviceSources::toSourceId);
446         }
447
448         public SchemaSourceProvider<YangTextSchemaSource> getSourceProvider() {
449             return sourceProvider;
450         }
451
452         private static SourceIdentifier toSourceId(final QName input) {
453             return RevisionSourceIdentifier.create(input.getLocalName(), input.getRevision());
454         }
455     }
456
457     /**
458      * Schema builder that tries to build schema context from provided sources or biggest subset of it.
459      */
460     private final class SchemaSetup implements Runnable {
461         private final DeviceSources deviceSources;
462         private final NetconfSessionPreferences remoteSessionCapabilities;
463         private final RemoteDeviceCommunicator<NetconfMessage> listener;
464         private final NetconfDeviceCapabilities capabilities;
465
466         SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities,
467                            final RemoteDeviceCommunicator<NetconfMessage> listener) {
468             this.deviceSources = deviceSources;
469             this.remoteSessionCapabilities = remoteSessionCapabilities;
470             this.listener = listener;
471             this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
472         }
473
474         @Override
475         public void run() {
476
477             final Collection<SourceIdentifier> requiredSources = deviceSources.getRequiredSources();
478             final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
479
480             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
481                     UnavailableCapability.FailureReason.MissingSource);
482
483             requiredSources.removeAll(missingSources);
484             setUpSchema(requiredSources);
485         }
486
487         private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> requiredSources) {
488             return requiredSources.parallelStream().filter(sourceIdentifier -> {
489                 try {
490                     schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
491                     return false;
492                 } catch (InterruptedException | ExecutionException e) {
493                     return true;
494                 }
495             }).collect(Collectors.toList());
496         }
497
498         /**
499          * Build schema context, in case of success or final failure notify device.
500          *
501          * @param requiredSources required sources
502          */
503         @SuppressWarnings("checkstyle:IllegalCatch")
504         private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
505             while (!requiredSources.isEmpty()) {
506                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
507                 try {
508                     final ListenableFuture<SchemaContext> schemaBuilderFuture = schemaContextFactory
509                             .createSchemaContext(requiredSources);
510                     final SchemaContext result = schemaBuilderFuture.get();
511                     LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
512                     final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
513                             capabilities.getUnresolvedCapabilites().keySet());
514                     capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
515                             .setCapability(entry.toString()).setCapabilityOrigin(
516                                     remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
517                             .collect(Collectors.toList()));
518
519                     capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
520                             .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
521                                     .setCapability(entry).setCapabilityOrigin(
522                                             remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
523                             .collect(Collectors.toList()));
524
525                     final MountPointContext mountContext = new EmptyMountPointContext(result);
526                     handleSalInitializationSuccess(mountContext, remoteSessionCapabilities,
527                         getDeviceSpecificRpc(mountContext), listener);
528                     return;
529                 } catch (final ExecutionException e) {
530                     // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
531                     // that might be wrapping a MissingSchemaSourceException so we need to look
532                     // at the cause of the exception to make sure we don't misinterpret it.
533                     final Throwable cause = e.getCause();
534
535                     if (cause instanceof MissingSchemaSourceException) {
536                         requiredSources = handleMissingSchemaSourceException(
537                                 requiredSources, (MissingSchemaSourceException) cause);
538                         continue;
539                     }
540                     if (cause instanceof SchemaResolutionException) {
541                         requiredSources = handleSchemaResolutionException(requiredSources,
542                             (SchemaResolutionException) cause);
543                     } else {
544                         handleSalInitializationFailure(e, listener);
545                         return;
546                     }
547                 } catch (final Exception e) {
548                     // unknown error, fail
549                     handleSalInitializationFailure(e, listener);
550                     return;
551                 }
552             }
553             // No more sources, fail or try to reconnect
554             if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().isAllowed()) {
555                 eventExecutor.schedule(() -> {
556                     LOG.warn("Reconnection is allowed! This can lead to unexpected errors at runtime.");
557                     LOG.warn("{} : No more sources for schema context.", id);
558                     LOG.info("{} : Try to remount device.", id);
559                     onRemoteSessionDown();
560                     salFacade.onDeviceReconnected(remoteSessionCapabilities, node);
561                 }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime(), TimeUnit.MILLISECONDS);
562             } else {
563                 final IllegalStateException cause =
564                         new IllegalStateException(id + ": No more sources for schema context");
565                 handleSalInitializationFailure(cause, listener);
566                 salFacade.onDeviceFailed(cause);
567             }
568         }
569
570         private Collection<SourceIdentifier> handleMissingSchemaSourceException(
571                 final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException exception) {
572             // In case source missing, try without it
573             final SourceIdentifier missingSource = exception.getSourceId();
574             LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
575                 id, missingSource);
576             LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
577                 id, missingSource, exception);
578             final Collection<QName> qNameOfMissingSource =
579                 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
580             if (!qNameOfMissingSource.isEmpty()) {
581                 capabilities.addUnresolvedCapabilities(
582                         qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
583             }
584             return stripUnavailableSource(requiredSources, missingSource);
585         }
586
587         private Collection<SourceIdentifier> handleSchemaResolutionException(
588             final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
589             // In case resolution error, try only with resolved sources
590             // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
591             // FIXME Do we really have assurance that these two cases cannot happen at once?
592             if (resolutionException.getFailedSource() != null) {
593                 // flawed model - exclude it
594                 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
595                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
596                     id, failedSourceId);
597                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
598                     id, failedSourceId, resolutionException);
599                 capabilities.addUnresolvedCapabilities(
600                         getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
601                         UnavailableCapability.FailureReason.UnableToResolve);
602                 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
603             }
604             // unsatisfied imports
605             final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
606             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
607                 UnavailableCapability.FailureReason.UnableToResolve);
608             LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
609                 id, resolutionException.getUnsatisfiedImports());
610             LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
611                 id, resolutionException.getUnsatisfiedImports(), resolutionException);
612             return resolutionException.getResolvedSources();
613         }
614
615         protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result) {
616             return new NetconfDeviceRpc(result.getSchemaContext(), listener,
617                 new NetconfMessageTransformer(result, true));
618         }
619
620         private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources,
621                                                                     final SourceIdentifier sourceIdToRemove) {
622             final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
623             checkState(sourceIdentifiers.remove(sourceIdToRemove),
624                     "%s: Trying to remove %s from %s failed", id, sourceIdToRemove, requiredSources);
625             return sourceIdentifiers;
626         }
627
628         private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
629             final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
630
631             if (qNames.isEmpty()) {
632                 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
633                         identifiers);
634             }
635             return Collections2.filter(qNames, Predicates.notNull());
636         }
637
638         private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
639             // Required sources are all required and provided merged in DeviceSourcesResolver
640             for (final QName qname : deviceSources.getRequiredSourcesQName()) {
641                 if (!qname.getLocalName().equals(identifier.getName())) {
642                     continue;
643                 }
644
645                 if (identifier.getRevision().equals(qname.getRevision())) {
646                     return qname;
647                 }
648             }
649             LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
650                     deviceSources.getRequiredSourcesQName());
651             // return null since we cannot find the QName,
652             // this capability will be removed from required sources and not reported as unresolved-capability
653             return null;
654         }
655     }
656 }