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