Introduce CREATE_SUBSCRIPTION_RPC_PATH
[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 com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12
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.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 io.netty.util.concurrent.EventExecutor;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.Optional;
29 import java.util.Set;
30 import java.util.concurrent.Callable;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.TimeUnit;
33 import java.util.stream.Collectors;
34 import org.checkerframework.checker.lock.qual.GuardedBy;
35 import org.opendaylight.mdsal.dom.api.DOMNotification;
36 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
37 import org.opendaylight.mdsal.dom.api.DOMRpcService;
38 import org.opendaylight.netconf.api.NetconfMessage;
39 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
40 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
41 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
42 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
43 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
44 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
45 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
47 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
49 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
50 import org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
51 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
52 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
53 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
54 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
55 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.optional.rev190614.NetconfNodeAugmentedOptional;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
61 import org.opendaylight.yangtools.yang.common.QName;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
64 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
65 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
66 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
67 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
68 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
69 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
70 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
71 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
72 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
73 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
74 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77
78 /**
79  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
80  */
81 public class NetconfDevice
82         implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
83
84     private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
85
86     protected final RemoteDeviceId id;
87     protected final SchemaContextFactory schemaContextFactory;
88     protected final SchemaSourceRegistry schemaRegistry;
89     protected final SchemaRepository schemaRepository;
90
91     protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations =
92             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(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 ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
203                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_PATH,
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             // salFacade.onDeviceConnected has to be called before the notification handler is initialized
255             this.salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
256                     this.deviceActionFactory == null ? null : this.deviceActionFactory.createDeviceAction(
257                             this.messageTransformer, listener, result));
258             this.notificationHandler.onRemoteSchemaUp(this.messageTransformer);
259
260             LOG.info("{}: Netconf connector initialized successfully", id);
261         } else {
262             LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
263         }
264     }
265
266     private void handleSalInitializationFailure(final Throwable throwable,
267                                                 final RemoteDeviceCommunicator<NetconfMessage> listener) {
268         LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
269         listener.close();
270         onRemoteSessionDown();
271         resetMessageTransformer();
272     }
273
274     /**
275      * Set the transformer to null as is in initial state.
276      */
277     private void resetMessageTransformer() {
278         updateTransformer(null);
279     }
280
281     private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
282         messageTransformer = transformer;
283     }
284
285     private synchronized void setConnected(final boolean connected) {
286         this.connected = connected;
287     }
288
289     private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
290         final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
291         for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
292             sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
293                     PotentialSchemaSource.create(
294                             sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
295         }
296     }
297
298     @Override
299     public void onRemoteSessionDown() {
300         setConnected(false);
301         notificationHandler.onRemoteSchemaDown();
302
303         salFacade.onDeviceDisconnected();
304         for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration
305                 : sourceRegistrations) {
306             sourceRegistration.close();
307         }
308         resetMessageTransformer();
309     }
310
311     @Override
312     public void onRemoteSessionFailed(final Throwable throwable) {
313         setConnected(false);
314         salFacade.onDeviceFailed(throwable);
315     }
316
317     @Override
318     public void onNotification(final NetconfMessage notification) {
319         notificationHandler.handleNotification(notification);
320     }
321
322     /**
323      * Just a transfer object containing schema related dependencies. Injected in constructor.
324      */
325     public static class SchemaResourcesDTO {
326         private final SchemaSourceRegistry schemaRegistry;
327         private final SchemaRepository schemaRepository;
328         private final SchemaContextFactory schemaContextFactory;
329         private final NetconfDeviceSchemasResolver stateSchemasResolver;
330
331         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
332                                   final SchemaRepository schemaRepository,
333                                   final SchemaContextFactory schemaContextFactory,
334                                   final NetconfDeviceSchemasResolver deviceSchemasResolver) {
335             this.schemaRegistry = requireNonNull(schemaRegistry);
336             this.schemaRepository = requireNonNull(schemaRepository);
337             this.schemaContextFactory = requireNonNull(schemaContextFactory);
338             this.stateSchemasResolver = requireNonNull(deviceSchemasResolver);
339         }
340
341         public SchemaSourceRegistry getSchemaRegistry() {
342             return schemaRegistry;
343         }
344
345         public SchemaRepository getSchemaRepository() {
346             return schemaRepository;
347         }
348
349         public SchemaContextFactory getSchemaContextFactory() {
350             return schemaContextFactory;
351         }
352
353         public NetconfDeviceSchemasResolver getStateSchemasResolver() {
354             return stateSchemasResolver;
355         }
356     }
357
358     /**
359      * Schema building callable.
360      */
361     private static class DeviceSourcesResolver implements Callable<DeviceSources> {
362
363         private final NetconfDeviceRpc deviceRpc;
364         private final NetconfSessionPreferences remoteSessionCapabilities;
365         private final RemoteDeviceId id;
366         private final NetconfDeviceSchemasResolver stateSchemasResolver;
367         private final SchemaContext schemaContext;
368
369         DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc,
370                               final NetconfSessionPreferences remoteSessionCapabilities,
371                               final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver,
372                               final SchemaContext schemaContext) {
373             this.deviceRpc = deviceRpc;
374             this.remoteSessionCapabilities = remoteSessionCapabilities;
375             this.id = id;
376             this.stateSchemasResolver = stateSchemasResolver;
377             this.schemaContext = schemaContext;
378         }
379
380         DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
381                                      final NetconfDeviceSchemasResolver stateSchemasResolver,
382                                      final NetconfDeviceRpc rpcForMonitoring, final SchemaContext schemaCtx) {
383             this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver, schemaCtx);
384         }
385
386         @Override
387         public DeviceSources call() {
388             final NetconfDeviceSchemas availableSchemas =
389                     stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id, schemaContext);
390             LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id,
391                     availableSchemas.getAvailableYangSchemasQNames());
392
393             final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
394             final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
395
396             final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
397             if (!requiredSourcesNotProvided.isEmpty()) {
398                 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities,"
399                         + " required but not provided: {}", id, requiredSourcesNotProvided);
400                 LOG.warn("{}: Attempting to build schema context from required sources", id);
401             }
402
403             // Here all the sources reported in netconf monitoring are merged with those reported in hello.
404             // It is necessary to perform this since submodules are not mentioned in hello but still required.
405             // This clashes with the option of a user to specify supported yang models manually in configuration
406             // for netconf-connector and as a result one is not able to fully override yang models of a device.
407             // It is only possible to add additional models.
408             final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
409             if (!providedSourcesNotRequired.isEmpty()) {
410                 LOG.warn("{}: Netconf device provides additional yang models not reported in "
411                         + "hello message capabilities: {}", id, providedSourcesNotRequired);
412                 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
413                 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
414                 requiredSources.addAll(providedSourcesNotRequired);
415             }
416
417             final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
418             if (availableSchemas instanceof LibraryModulesSchemas) {
419                 sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
420                         ((LibraryModulesSchemas) availableSchemas).getAvailableModels());
421             } else {
422                 sourceProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
423             }
424
425             return new DeviceSources(requiredSources, providedSources, sourceProvider);
426         }
427     }
428
429     /**
430      * Contains RequiredSources - sources from capabilities.
431      */
432     private static final class DeviceSources {
433         private final Set<QName> requiredSources;
434         private final Set<QName> providedSources;
435         private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
436
437         DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
438                              final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
439             this.requiredSources = requiredSources;
440             this.providedSources = providedSources;
441             this.sourceProvider = sourceProvider;
442         }
443
444         public Set<QName> getRequiredSourcesQName() {
445             return requiredSources;
446         }
447
448         public Set<QName> getProvidedSourcesQName() {
449             return providedSources;
450         }
451
452         public Collection<SourceIdentifier> getRequiredSources() {
453             return Collections2.transform(requiredSources, DeviceSources::toSourceId);
454         }
455
456         public Collection<SourceIdentifier> getProvidedSources() {
457             return Collections2.transform(providedSources, DeviceSources::toSourceId);
458         }
459
460         public SchemaSourceProvider<YangTextSchemaSource> getSourceProvider() {
461             return sourceProvider;
462         }
463
464         private static SourceIdentifier toSourceId(final QName input) {
465             return RevisionSourceIdentifier.create(input.getLocalName(), input.getRevision());
466         }
467     }
468
469     /**
470      * Schema builder that tries to build schema context from provided sources or biggest subset of it.
471      */
472     private final class SchemaSetup implements Runnable {
473         private final DeviceSources deviceSources;
474         private final NetconfSessionPreferences remoteSessionCapabilities;
475         private final RemoteDeviceCommunicator<NetconfMessage> listener;
476         private final NetconfDeviceCapabilities capabilities;
477
478         SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities,
479                            final RemoteDeviceCommunicator<NetconfMessage> listener) {
480             this.deviceSources = deviceSources;
481             this.remoteSessionCapabilities = remoteSessionCapabilities;
482             this.listener = listener;
483             this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
484         }
485
486         @Override
487         public void run() {
488
489             final Collection<SourceIdentifier> requiredSources = deviceSources.getRequiredSources();
490             final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
491
492             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
493                     UnavailableCapability.FailureReason.MissingSource);
494
495             requiredSources.removeAll(missingSources);
496             setUpSchema(requiredSources);
497         }
498
499         private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> requiredSources) {
500             return requiredSources.parallelStream().filter(sourceIdentifier -> {
501                 try {
502                     schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
503                     return false;
504                 } catch (InterruptedException | ExecutionException e) {
505                     return true;
506                 }
507             }).collect(Collectors.toList());
508         }
509
510         /**
511          * Build schema context, in case of success or final failure notify device.
512          *
513          * @param requiredSources required sources
514          */
515         @SuppressWarnings("checkstyle:IllegalCatch")
516         private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
517             while (!requiredSources.isEmpty()) {
518                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
519                 try {
520                     final ListenableFuture<SchemaContext> schemaBuilderFuture = schemaContextFactory
521                             .createSchemaContext(requiredSources);
522                     final SchemaContext result = schemaBuilderFuture.get();
523                     LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
524                     final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
525                             capabilities.getUnresolvedCapabilites().keySet());
526                     capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
527                             .setCapability(entry.toString()).setCapabilityOrigin(
528                                     remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
529                             .collect(Collectors.toList()));
530
531                     capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
532                             .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
533                                     .setCapability(entry).setCapabilityOrigin(
534                                             remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
535                             .collect(Collectors.toList()));
536
537                     handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result),
538                             listener);
539                     return;
540                 } catch (final ExecutionException e) {
541                     // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
542                     // that might be wrapping a MissingSchemaSourceException so we need to look
543                     // at the cause of the exception to make sure we don't misinterpret it.
544                     final Throwable cause = e.getCause();
545
546                     if (cause instanceof MissingSchemaSourceException) {
547                         requiredSources = handleMissingSchemaSourceException(
548                                 requiredSources, (MissingSchemaSourceException) cause);
549                         continue;
550                     }
551                     if (cause instanceof SchemaResolutionException) {
552                         requiredSources = handleSchemaResolutionException(requiredSources,
553                             (SchemaResolutionException) cause);
554                     } else {
555                         handleSalInitializationFailure(e, listener);
556                         return;
557                     }
558                 } catch (final Exception e) {
559                     // unknown error, fail
560                     handleSalInitializationFailure(e, listener);
561                     return;
562                 }
563             }
564             // No more sources, fail or try to reconnect
565             if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().isAllowed()) {
566                 eventExecutor.schedule(() -> {
567                     LOG.warn("Reconnection is allowed! This can lead to unexpected errors at runtime.");
568                     LOG.warn("{} : No more sources for schema context.", id);
569                     LOG.info("{} : Try to remount device.", id);
570                     onRemoteSessionDown();
571                     salFacade.onDeviceReconnected(remoteSessionCapabilities, node);
572                 }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime(), TimeUnit.MILLISECONDS);
573             } else {
574                 final IllegalStateException cause =
575                         new IllegalStateException(id + ": No more sources for schema context");
576                 handleSalInitializationFailure(cause, listener);
577                 salFacade.onDeviceFailed(cause);
578             }
579         }
580
581         private Collection<SourceIdentifier> handleMissingSchemaSourceException(
582                 final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException exception) {
583             // In case source missing, try without it
584             final SourceIdentifier missingSource = exception.getSourceId();
585             LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
586                 id, missingSource);
587             LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
588                 id, missingSource, exception);
589             final Collection<QName> qNameOfMissingSource =
590                 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
591             if (!qNameOfMissingSource.isEmpty()) {
592                 capabilities.addUnresolvedCapabilities(
593                         qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
594             }
595             return stripUnavailableSource(requiredSources, missingSource);
596         }
597
598         private Collection<SourceIdentifier> handleSchemaResolutionException(
599             final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
600             // In case resolution error, try only with resolved sources
601             // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
602             // FIXME Do we really have assurance that these two cases cannot happen at once?
603             if (resolutionException.getFailedSource() != null) {
604                 // flawed model - exclude it
605                 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
606                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
607                     id, failedSourceId);
608                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
609                     id, failedSourceId, resolutionException);
610                 capabilities.addUnresolvedCapabilities(
611                         getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
612                         UnavailableCapability.FailureReason.UnableToResolve);
613                 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
614             }
615             // unsatisfied imports
616             final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
617             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
618                 UnavailableCapability.FailureReason.UnableToResolve);
619             LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
620                 id, resolutionException.getUnsatisfiedImports());
621             LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
622                 id, resolutionException.getUnsatisfiedImports(), resolutionException);
623             return resolutionException.getResolvedSources();
624         }
625
626         protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
627             return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
628         }
629
630         private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources,
631                                                                     final SourceIdentifier sourceIdToRemove) {
632             final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
633             checkState(sourceIdentifiers.remove(sourceIdToRemove),
634                     "%s: Trying to remove %s from %s 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 }