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