fc100b3db80a2ec232db0ad3e15ceb8fdb0f7e42
[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.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(@Nonnull 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 synchronized 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() {
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(), input.getRevision());
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             return requiredSources.parallelStream().filter(sourceIdentifier -> {
470                 try {
471                     schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
472                     return false;
473                 } catch (InterruptedException | ExecutionException e) {
474                     return true;
475                 }
476             }).collect(Collectors.toList());
477         }
478
479         /**
480          * Build schema context, in case of success or final failure notify device.
481          */
482         @SuppressWarnings("checkstyle:IllegalCatch")
483         private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
484             while (!requiredSources.isEmpty()) {
485                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
486                 try {
487                     final ListenableFuture<SchemaContext> schemaBuilderFuture = schemaContextFactory
488                             .createSchemaContext(requiredSources);
489                     final SchemaContext result = schemaBuilderFuture.get();
490                     LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
491                     final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
492                             capabilities.getUnresolvedCapabilites().keySet());
493                     capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
494                             .setCapability(entry.toString()).setCapabilityOrigin(
495                                     remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
496                             .collect(Collectors.toList()));
497
498                     capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
499                             .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
500                                     .setCapability(entry).setCapabilityOrigin(
501                                             remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
502                             .collect(Collectors.toList()));
503
504                     handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
505                     return;
506                 } catch (final ExecutionException e) {
507                     // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
508                     // that might be wrapping a MissingSchemaSourceException so we need to look
509                     // at the cause of the exception to make sure we don't misinterpret it.
510                     final Throwable cause = e.getCause();
511
512                     if (cause instanceof MissingSchemaSourceException) {
513                         requiredSources = handleMissingSchemaSourceException(
514                                 requiredSources, (MissingSchemaSourceException) cause);
515                         continue;
516                     }
517                     if (cause instanceof SchemaResolutionException) {
518                         requiredSources = handleSchemaResolutionException(requiredSources,
519                             (SchemaResolutionException) cause);
520                     } else {
521                         handleSalInitializationFailure(e, listener);
522                         return;
523                     }
524                 } catch (final Exception e) {
525                     // unknown error, fail
526                     handleSalInitializationFailure(e, listener);
527                     return;
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",
541                 id, missingSource);
542             LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
543                 id, missingSource, 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, failedSourceId, resolutionException);
565                 capabilities.addUnresolvedCapabilities(
566                         getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
567                         UnavailableCapability.FailureReason.UnableToResolve);
568                 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
569             }
570             // unsatisfied imports
571             final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
572             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
573                 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                 id, resolutionException.getUnsatisfiedImports(), 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 }