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