Remove duplicate assignment
[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             // salFacade.onDeviceConnected has to be called before the notification handler is initialized
240             this.salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
241                     this.deviceActionFactory == null ? null : this.deviceActionFactory.createDeviceAction(
242                             this.messageTransformer, listener, result));
243             this.notificationHandler.onRemoteSchemaUp(this.messageTransformer);
244
245             LOG.info("{}: Netconf connector initialized successfully", id);
246         } else {
247             LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
248         }
249     }
250
251     private void handleSalInitializationFailure(final Throwable throwable,
252                                                 final RemoteDeviceCommunicator<NetconfMessage> listener) {
253         LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
254         listener.close();
255         onRemoteSessionDown();
256         resetMessageTransformer();
257     }
258
259     /**
260      * Set the transformer to null as is in initial state.
261      */
262     private void resetMessageTransformer() {
263         updateTransformer(null);
264     }
265
266     private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
267         messageTransformer = transformer;
268     }
269
270     private synchronized void setConnected(final boolean connected) {
271         this.connected = connected;
272     }
273
274     private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
275         final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
276         for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
277             sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
278                     PotentialSchemaSource.create(
279                             sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
280         }
281     }
282
283     @Override
284     public void onRemoteSessionDown() {
285         setConnected(false);
286         notificationHandler.onRemoteSchemaDown();
287
288         salFacade.onDeviceDisconnected();
289         for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration
290                 : sourceRegistrations) {
291             sourceRegistration.close();
292         }
293         resetMessageTransformer();
294     }
295
296     @Override
297     public void onRemoteSessionFailed(final Throwable throwable) {
298         setConnected(false);
299         salFacade.onDeviceFailed(throwable);
300     }
301
302     @Override
303     public void onNotification(final NetconfMessage notification) {
304         notificationHandler.handleNotification(notification);
305     }
306
307     /**
308      * Just a transfer object containing schema related dependencies. Injected in constructor.
309      */
310     public static class SchemaResourcesDTO {
311         private final SchemaSourceRegistry schemaRegistry;
312         private final SchemaRepository schemaRepository;
313         private final SchemaContextFactory schemaContextFactory;
314         private final NetconfDeviceSchemasResolver stateSchemasResolver;
315
316         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
317                                   final SchemaRepository schemaRepository,
318                                   final SchemaContextFactory schemaContextFactory,
319                                   final NetconfDeviceSchemasResolver deviceSchemasResolver) {
320             this.schemaRegistry = requireNonNull(schemaRegistry);
321             this.schemaRepository = requireNonNull(schemaRepository);
322             this.schemaContextFactory = requireNonNull(schemaContextFactory);
323             this.stateSchemasResolver = requireNonNull(deviceSchemasResolver);
324         }
325
326         public SchemaSourceRegistry getSchemaRegistry() {
327             return schemaRegistry;
328         }
329
330         public SchemaRepository getSchemaRepository() {
331             return schemaRepository;
332         }
333
334         public SchemaContextFactory getSchemaContextFactory() {
335             return schemaContextFactory;
336         }
337
338         public NetconfDeviceSchemasResolver getStateSchemasResolver() {
339             return stateSchemasResolver;
340         }
341     }
342
343     /**
344      * Schema building callable.
345      */
346     private static class DeviceSourcesResolver implements Callable<DeviceSources> {
347
348         private final NetconfDeviceRpc deviceRpc;
349         private final NetconfSessionPreferences remoteSessionCapabilities;
350         private final RemoteDeviceId id;
351         private final NetconfDeviceSchemasResolver stateSchemasResolver;
352
353         DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc,
354                               final NetconfSessionPreferences remoteSessionCapabilities,
355                               final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver) {
356             this.deviceRpc = deviceRpc;
357             this.remoteSessionCapabilities = remoteSessionCapabilities;
358             this.id = id;
359             this.stateSchemasResolver = stateSchemasResolver;
360         }
361
362         DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
363                                      final NetconfDeviceSchemasResolver stateSchemasResolver,
364                                      final NetconfDeviceRpc rpcForMonitoring) {
365             this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver);
366         }
367
368         @Override
369         public DeviceSources call() {
370             final NetconfDeviceSchemas availableSchemas =
371                     stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
372             LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id,
373                     availableSchemas.getAvailableYangSchemasQNames());
374
375             final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
376             final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
377
378             final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
379             if (!requiredSourcesNotProvided.isEmpty()) {
380                 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities,"
381                         + " required but not provided: {}", id, requiredSourcesNotProvided);
382                 LOG.warn("{}: Attempting to build schema context from required sources", id);
383             }
384
385             // Here all the sources reported in netconf monitoring are merged with those reported in hello.
386             // It is necessary to perform this since submodules are not mentioned in hello but still required.
387             // This clashes with the option of a user to specify supported yang models manually in configuration
388             // for netconf-connector and as a result one is not able to fully override yang models of a device.
389             // It is only possible to add additional models.
390             final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
391             if (!providedSourcesNotRequired.isEmpty()) {
392                 LOG.warn("{}: Netconf device provides additional yang models not reported in "
393                         + "hello message capabilities: {}", id, providedSourcesNotRequired);
394                 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
395                 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
396                 requiredSources.addAll(providedSourcesNotRequired);
397             }
398
399             final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
400             if (availableSchemas instanceof LibraryModulesSchemas) {
401                 sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
402                         ((LibraryModulesSchemas) availableSchemas).getAvailableModels());
403             } else {
404                 sourceProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
405             }
406
407             return new DeviceSources(requiredSources, providedSources, sourceProvider);
408         }
409     }
410
411     /**
412      * Contains RequiredSources - sources from capabilities.
413      */
414     private static final class DeviceSources {
415         private final Set<QName> requiredSources;
416         private final Set<QName> providedSources;
417         private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
418
419         DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
420                              final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
421             this.requiredSources = requiredSources;
422             this.providedSources = providedSources;
423             this.sourceProvider = sourceProvider;
424         }
425
426         public Set<QName> getRequiredSourcesQName() {
427             return requiredSources;
428         }
429
430         public Set<QName> getProvidedSourcesQName() {
431             return providedSources;
432         }
433
434         public Collection<SourceIdentifier> getRequiredSources() {
435             return Collections2.transform(requiredSources, DeviceSources::toSourceId);
436         }
437
438         public Collection<SourceIdentifier> getProvidedSources() {
439             return Collections2.transform(providedSources, DeviceSources::toSourceId);
440         }
441
442         public SchemaSourceProvider<YangTextSchemaSource> getSourceProvider() {
443             return sourceProvider;
444         }
445
446         private static SourceIdentifier toSourceId(final QName input) {
447             return RevisionSourceIdentifier.create(input.getLocalName(), input.getRevision());
448         }
449     }
450
451     /**
452      * Schema builder that tries to build schema context from provided sources or biggest subset of it.
453      */
454     private final class SchemaSetup implements Runnable {
455         private final DeviceSources deviceSources;
456         private final NetconfSessionPreferences remoteSessionCapabilities;
457         private final RemoteDeviceCommunicator<NetconfMessage> listener;
458         private final NetconfDeviceCapabilities capabilities;
459
460         SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities,
461                            final RemoteDeviceCommunicator<NetconfMessage> listener) {
462             this.deviceSources = deviceSources;
463             this.remoteSessionCapabilities = remoteSessionCapabilities;
464             this.listener = listener;
465             this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
466         }
467
468         @Override
469         public void run() {
470
471             final Collection<SourceIdentifier> requiredSources = deviceSources.getRequiredSources();
472             final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
473
474             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
475                     UnavailableCapability.FailureReason.MissingSource);
476
477             requiredSources.removeAll(missingSources);
478             setUpSchema(requiredSources);
479         }
480
481         private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> requiredSources) {
482             return requiredSources.parallelStream().filter(sourceIdentifier -> {
483                 try {
484                     schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
485                     return false;
486                 } catch (InterruptedException | ExecutionException e) {
487                     return true;
488                 }
489             }).collect(Collectors.toList());
490         }
491
492         /**
493          * Build schema context, in case of success or final failure notify device.
494          *
495          * @param requiredSources required sources
496          */
497         @SuppressWarnings("checkstyle:IllegalCatch")
498         private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
499             while (!requiredSources.isEmpty()) {
500                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
501                 try {
502                     final ListenableFuture<SchemaContext> schemaBuilderFuture = schemaContextFactory
503                             .createSchemaContext(requiredSources);
504                     final SchemaContext result = schemaBuilderFuture.get();
505                     LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
506                     final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
507                             capabilities.getUnresolvedCapabilites().keySet());
508                     capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
509                             .setCapability(entry.toString()).setCapabilityOrigin(
510                                     remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
511                             .collect(Collectors.toList()));
512
513                     capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
514                             .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
515                                     .setCapability(entry).setCapabilityOrigin(
516                                             remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
517                             .collect(Collectors.toList()));
518
519                     handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result),
520                             listener);
521                     return;
522                 } catch (final ExecutionException e) {
523                     // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
524                     // that might be wrapping a MissingSchemaSourceException so we need to look
525                     // at the cause of the exception to make sure we don't misinterpret it.
526                     final Throwable cause = e.getCause();
527
528                     if (cause instanceof MissingSchemaSourceException) {
529                         requiredSources = handleMissingSchemaSourceException(
530                                 requiredSources, (MissingSchemaSourceException) cause);
531                         continue;
532                     }
533                     if (cause instanceof SchemaResolutionException) {
534                         requiredSources = handleSchemaResolutionException(requiredSources,
535                             (SchemaResolutionException) cause);
536                     } else {
537                         handleSalInitializationFailure(e, listener);
538                         return;
539                     }
540                 } catch (final Exception e) {
541                     // unknown error, fail
542                     handleSalInitializationFailure(e, listener);
543                     return;
544                 }
545             }
546             // No more sources, fail
547             final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context");
548             handleSalInitializationFailure(cause, listener);
549             salFacade.onDeviceFailed(cause);
550         }
551
552         private Collection<SourceIdentifier> handleMissingSchemaSourceException(
553                 final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException exception) {
554             // In case source missing, try without it
555             final SourceIdentifier missingSource = exception.getSourceId();
556             LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
557                 id, missingSource);
558             LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
559                 id, missingSource, exception);
560             final Collection<QName> qNameOfMissingSource =
561                 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
562             if (!qNameOfMissingSource.isEmpty()) {
563                 capabilities.addUnresolvedCapabilities(
564                         qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
565             }
566             return stripUnavailableSource(requiredSources, missingSource);
567         }
568
569         private Collection<SourceIdentifier> handleSchemaResolutionException(
570             final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
571             // In case resolution error, try only with resolved sources
572             // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
573             // FIXME Do we really have assurance that these two cases cannot happen at once?
574             if (resolutionException.getFailedSource() != null) {
575                 // flawed model - exclude it
576                 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
577                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
578                     id, failedSourceId);
579                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
580                     id, failedSourceId, resolutionException);
581                 capabilities.addUnresolvedCapabilities(
582                         getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
583                         UnavailableCapability.FailureReason.UnableToResolve);
584                 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
585             }
586             // unsatisfied imports
587             final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
588             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
589                 UnavailableCapability.FailureReason.UnableToResolve);
590             LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
591                 id, resolutionException.getUnsatisfiedImports());
592             LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
593                 id, resolutionException.getUnsatisfiedImports(), resolutionException);
594             return resolutionException.getResolvedSources();
595         }
596
597         protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
598             return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
599         }
600
601         private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources,
602                                                                     final SourceIdentifier sourceIdToRemove) {
603             final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
604             checkState(sourceIdentifiers.remove(sourceIdToRemove),
605                     "%s: Trying to remove %s from %s failed", id, sourceIdToRemove, requiredSources);
606             return sourceIdentifiers;
607         }
608
609         private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
610             final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
611
612             if (qNames.isEmpty()) {
613                 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
614                         identifiers);
615             }
616             return Collections2.filter(qNames, Predicates.notNull());
617         }
618
619         private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
620             // Required sources are all required and provided merged in DeviceSourcesResolver
621             for (final QName qname : deviceSources.getRequiredSourcesQName()) {
622                 if (!qname.getLocalName().equals(identifier.getName())) {
623                     continue;
624                 }
625
626                 if (identifier.getRevision().equals(qname.getRevision())) {
627                     return qname;
628                 }
629             }
630             LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
631                     deviceSources.getRequiredSourcesQName());
632             // return null since we cannot find the QName,
633             // this capability will be removed from required sources and not reported as unresolved-capability
634             return null;
635         }
636     }
637 }