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