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