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