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