Bump upstream versions
[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 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
13
14 import com.google.common.base.Predicates;
15 import com.google.common.collect.Collections2;
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 com.google.common.util.concurrent.SettableFuture;
23 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24 import io.netty.util.concurrent.EventExecutor;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.LinkedList;
30 import java.util.List;
31 import java.util.Objects;
32 import java.util.Optional;
33 import java.util.Set;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.TimeUnit;
36 import java.util.stream.Collectors;
37 import org.checkerframework.checker.lock.qual.GuardedBy;
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.api.xml.XmlNetconfConstants;
42 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
43 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
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.mapping.BaseNetconfSchemas;
53 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
54 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
55 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
56 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.optional.rev190614.NetconfNodeAugmentedOptional;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
62 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
63 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
64 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
65 import org.opendaylight.yangtools.yang.common.QName;
66 import org.opendaylight.yangtools.yang.common.RpcError;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
71 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
72 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
73 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
74 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
75 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
76 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
77 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
78 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
79 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
80 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
81 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
82 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85
86 /**
87  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
88  */
89 public class NetconfDevice
90         implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
91
92     @SuppressFBWarnings(value = "SLF4J_LOGGER_SHOULD_BE_PRIVATE",
93             justification = "Needed for common logging of related classes")
94     static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
95
96     private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
97         SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
98     private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
99         NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
100
101     protected final RemoteDeviceId id;
102     protected final EffectiveModelContextFactory schemaContextFactory;
103     protected final SchemaSourceRegistry schemaRegistry;
104     protected final SchemaRepository schemaRepository;
105
106     protected final List<SchemaSourceRegistration<?>> sourceRegistrations = new ArrayList<>();
107
108     private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
109     private final ListeningExecutorService processingExecutor;
110     private final DeviceActionFactory deviceActionFactory;
111     private final NetconfDeviceSchemasResolver stateSchemasResolver;
112     private final NotificationHandler notificationHandler;
113     private final boolean reconnectOnSchemasChange;
114     private final BaseNetconfSchemas baseSchemas;
115     private final NetconfNode node;
116     private final EventExecutor eventExecutor;
117     private final NetconfNodeAugmentedOptional nodeOptional;
118
119     @GuardedBy("this")
120     private boolean connected = false;
121
122     // Message transformer is constructed once the schemas are available
123     private MessageTransformer<NetconfMessage> messageTransformer;
124
125     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
126             final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
127             final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
128         this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null,
129             null, null, null);
130     }
131
132     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
133             final RemoteDeviceId id, 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.baseSchemas = requireNonNull(baseSchemas);
138         this.id = id;
139         this.reconnectOnSchemasChange = reconnectOnSchemasChange;
140         this.deviceActionFactory = deviceActionFactory;
141         this.node = node;
142         this.eventExecutor = eventExecutor;
143         this.nodeOptional = nodeOptional;
144         schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
145         schemaRepository = schemaResourcesDTO.getSchemaRepository();
146         schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
147         this.salFacade = salFacade;
148         stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
149         processingExecutor = requireNonNull(globalProcessingExecutor);
150         notificationHandler = new NotificationHandler(salFacade, id);
151     }
152
153     @Override
154     public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
155                                   final NetconfDeviceCommunicator listener) {
156         // SchemaContext setup has to be performed in a dedicated thread since
157         // we are in a netty thread in this method
158         // Yang models are being downloaded in this method and it would cause a
159         // deadlock if we used the netty thread
160         // http://netty.io/wiki/thread-model.html
161         setConnected(true);
162         LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
163
164         final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
165         final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
166             new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
167         final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
168             new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
169
170         if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
171             registerToBaseNetconfStream(initRpc, listener);
172         }
173
174         // Set up the SchemaContext for the device
175         final ListenableFuture<EffectiveModelContext> futureSchema = Futures.transformAsync(sourceResolverFuture,
176             deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
177
178         // Potentially acquire mount point list and interpret it
179         final ListenableFuture<MountPointContext> futureContext = Futures.transformAsync(futureSchema,
180             schemaContext -> createMountPointContext(schemaContext, baseSchema, listener), processingExecutor);
181
182         Futures.addCallback(futureContext, new FutureCallback<MountPointContext>() {
183             @Override
184             public void onSuccess(final MountPointContext result) {
185                 handleSalInitializationSuccess(result, remoteSessionCapabilities,
186                         getDeviceSpecificRpc(result, listener, baseSchema), listener);
187             }
188
189             @Override
190             public void onFailure(final Throwable cause) {
191                 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
192
193                 // No more sources, fail or try to reconnect
194                 if (cause instanceof EmptySchemaContextException) {
195                     if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().getAllowed()) {
196                         eventExecutor.schedule(() -> {
197                             LOG.warn("Reconnection is allowed! This can lead to unexpected errors at runtime.");
198                             LOG.warn("{} : No more sources for schema context.", id);
199                             LOG.info("{} : Try to remount device.", id);
200                             onRemoteSessionDown();
201                             salFacade.onDeviceReconnected(remoteSessionCapabilities, node);
202                         }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime().toJava(),
203                             TimeUnit.MILLISECONDS);
204                         return;
205                     }
206                 }
207
208                 handleSalInitializationFailure(cause, listener);
209                 salFacade.onDeviceFailed(cause);
210             }
211         }, MoreExecutors.directExecutor());
212     }
213
214     private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
215                                              final NetconfDeviceCommunicator listener) {
216         // TODO check whether the model describing create subscription is present in schema
217         // Perhaps add a default schema context to support create-subscription if the model was not provided
218         // (same as what we do for base netconf operations in transformer)
219         final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
220                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
221                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
222
223         Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
224             @Override
225             public void onSuccess(final DOMRpcResult domRpcResult) {
226                 notificationHandler.addNotificationFilter(notification -> {
227                     if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getIdentifier().getNodeType())) {
228                         LOG.info("{}: Schemas change detected, reconnecting", id);
229                         // Only disconnect is enough,
230                         // the reconnecting nature of the connector will take care of reconnecting
231                         listener.disconnect();
232                         return Optional.empty();
233                     }
234                     return Optional.of(notification);
235                 });
236             }
237
238             @Override
239             public void onFailure(final Throwable throwable) {
240                 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
241                         throwable);
242             }
243         }, MoreExecutors.directExecutor());
244     }
245
246     private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
247         return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
248     }
249
250     private synchronized void handleSalInitializationSuccess(final MountPointContext result,
251                                         final NetconfSessionPreferences remoteSessionCapabilities,
252                                         final DOMRpcService deviceRpc,
253                                         final RemoteDeviceCommunicator<NetconfMessage> listener) {
254         //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
255         //since salFacade.onDeviceDisconnected was already called.
256         if (connected) {
257             messageTransformer = new NetconfMessageTransformer(result, true,
258                 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
259
260             // salFacade.onDeviceConnected has to be called before the notification handler is initialized
261             salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
262                     deviceActionFactory == null ? null : deviceActionFactory.createDeviceAction(
263                             messageTransformer, listener, result.getEffectiveModelContext()));
264             notificationHandler.onRemoteSchemaUp(messageTransformer);
265
266             LOG.info("{}: Netconf connector initialized successfully", id);
267         } else {
268             LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
269         }
270     }
271
272     private void handleSalInitializationFailure(final Throwable throwable,
273                                                 final RemoteDeviceCommunicator<NetconfMessage> listener) {
274         LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
275         listener.close();
276         onRemoteSessionDown();
277         resetMessageTransformer();
278     }
279
280     /**
281      * Set the transformer to null as is in initial state.
282      */
283     private void resetMessageTransformer() {
284         updateTransformer(null);
285     }
286
287     private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
288         messageTransformer = transformer;
289     }
290
291     private synchronized void setConnected(final boolean connected) {
292         this.connected = connected;
293     }
294
295     private ListenableFuture<EffectiveModelContext> assembleSchemaContext(final DeviceSources deviceSources,
296             final NetconfSessionPreferences remoteSessionCapabilities) {
297         LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
298         final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
299         for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
300             sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
301                 PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class,
302                     PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
303         }
304
305         return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
306     }
307
308     private ListenableFuture<MountPointContext> createMountPointContext(final EffectiveModelContext schemaContext,
309             final BaseSchema baseSchema, final NetconfDeviceCommunicator listener) {
310         final MountPointContext emptyContext = new EmptyMountPointContext(schemaContext);
311         if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
312             return Futures.immediateFuture(emptyContext);
313         }
314
315         // Create a temporary RPC invoker and acquire the mount point tree
316         LOG.debug("{}: Acquiring available mount points", id);
317         final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
318             new NetconfMessageTransformer(emptyContext, false, baseSchema));
319
320         return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
321             Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
322                 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
323                 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
324     }
325
326     private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
327         final Collection<? extends RpcError> errors = rpcResult.getErrors();
328         if (!errors.isEmpty()) {
329             LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
330         }
331         final NormalizedNode schemaMounts = rpcResult.getResult();
332         if (schemaMounts == null) {
333             LOG.debug("{}: device does not define any schema mounts", id);
334             return emptyContext;
335         }
336         if (!(schemaMounts instanceof ContainerNode)) {
337             LOG.warn("{}: ignoring non-container schema mounts {}", id, schemaMounts);
338             return emptyContext;
339         }
340
341         return DeviceMountPointContext.create(emptyContext, (ContainerNode) schemaMounts);
342     }
343
344     @Override
345     public void onRemoteSessionDown() {
346         setConnected(false);
347         notificationHandler.onRemoteSchemaDown();
348
349         salFacade.onDeviceDisconnected();
350         sourceRegistrations.forEach(SchemaSourceRegistration::close);
351         sourceRegistrations.clear();
352         resetMessageTransformer();
353     }
354
355     @Override
356     public void onRemoteSessionFailed(final Throwable throwable) {
357         setConnected(false);
358         salFacade.onDeviceFailed(throwable);
359     }
360
361     @Override
362     public void onNotification(final NetconfMessage notification) {
363         notificationHandler.handleNotification(notification);
364     }
365
366     private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
367         return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
368     }
369
370     protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
371             final RemoteDeviceCommunicator<NetconfMessage> listener, final BaseSchema schema) {
372         return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
373             new NetconfMessageTransformer(result, true, schema));
374     }
375
376     /**
377      * Just a transfer object containing schema related dependencies. Injected in constructor.
378      */
379     public static class SchemaResourcesDTO {
380         private final SchemaSourceRegistry schemaRegistry;
381         private final SchemaRepository schemaRepository;
382         private final EffectiveModelContextFactory schemaContextFactory;
383         private final NetconfDeviceSchemasResolver stateSchemasResolver;
384
385         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
386                                   final SchemaRepository schemaRepository,
387                                   final EffectiveModelContextFactory schemaContextFactory,
388                                   final NetconfDeviceSchemasResolver deviceSchemasResolver) {
389             this.schemaRegistry = requireNonNull(schemaRegistry);
390             this.schemaRepository = requireNonNull(schemaRepository);
391             this.schemaContextFactory = requireNonNull(schemaContextFactory);
392             stateSchemasResolver = requireNonNull(deviceSchemasResolver);
393         }
394
395         public SchemaSourceRegistry getSchemaRegistry() {
396             return schemaRegistry;
397         }
398
399         public SchemaRepository getSchemaRepository() {
400             return schemaRepository;
401         }
402
403         public EffectiveModelContextFactory getSchemaContextFactory() {
404             return schemaContextFactory;
405         }
406
407         public NetconfDeviceSchemasResolver getStateSchemasResolver() {
408             return stateSchemasResolver;
409         }
410     }
411
412     /**
413      * A dedicated exception to indicate when we fail to setup a SchemaContext.
414      *
415      * @author Robert Varga
416      */
417     private static final class EmptySchemaContextException extends Exception {
418         private static final long serialVersionUID = 1L;
419
420         EmptySchemaContextException(final String message) {
421             super(message);
422         }
423     }
424
425     /**
426      * Schema builder that tries to build schema context from provided sources or biggest subset of it.
427      */
428     private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
429         private final SettableFuture<EffectiveModelContext> resultFuture = SettableFuture.create();
430
431         private final DeviceSources deviceSources;
432         private final NetconfSessionPreferences remoteSessionCapabilities;
433         private final NetconfDeviceCapabilities capabilities;
434
435         private Collection<SourceIdentifier> requiredSources;
436
437         SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
438             this.deviceSources = deviceSources;
439             this.remoteSessionCapabilities = remoteSessionCapabilities;
440             capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
441
442             // If device supports notifications and does not contain necessary modules, add them automatically
443             if (remoteSessionCapabilities.containsNonModuleCapability(
444                     XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0)) {
445                 deviceSources.getRequiredSourcesQName().addAll(
446                         Arrays.asList(
447                                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
448                                         .$YangModuleInfoImpl.getInstance().getName(),
449                                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
450                                         .$YangModuleInfoImpl.getInstance().getName()
451                         )
452                 );
453             }
454
455             requiredSources = deviceSources.getRequiredSources();
456             final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
457
458             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
459                     UnavailableCapability.FailureReason.MissingSource);
460             requiredSources.removeAll(missingSources);
461         }
462
463         ListenableFuture<EffectiveModelContext> startResolution() {
464             trySetupSchema();
465             return resultFuture;
466         }
467
468         @Override
469         public void onSuccess(final EffectiveModelContext result) {
470             LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
471
472             final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
473                     capabilities.getUnresolvedCapabilites().keySet());
474             capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
475                     .setCapability(entry.toString()).setCapabilityOrigin(
476                             remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
477                     .collect(Collectors.toList()));
478
479             capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
480                     .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
481                             .setCapability(entry).setCapabilityOrigin(
482                                     remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
483                     .collect(Collectors.toList()));
484
485             resultFuture.set(result);
486         }
487
488         @Override
489         public void onFailure(final Throwable cause) {
490             // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
491             // that might be wrapping a MissingSchemaSourceException so we need to look
492             // at the cause of the exception to make sure we don't misinterpret it.
493             if (cause instanceof MissingSchemaSourceException) {
494                 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
495             } else if (cause instanceof SchemaResolutionException) {
496                 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
497             } else {
498                 LOG.debug("Unhandled failure", cause);
499                 resultFuture.setException(cause);
500                 // No more trying...
501                 return;
502             }
503
504             trySetupSchema();
505         }
506
507         private void trySetupSchema() {
508             if (!requiredSources.isEmpty()) {
509                 // Initiate async resolution, drive it back based on the result
510                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
511                 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
512                     MoreExecutors.directExecutor());
513             } else {
514                 LOG.debug("{}: no more sources for schema context", id);
515                 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
516             }
517         }
518
519         private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
520             return origSources.parallelStream().filter(sourceIdentifier -> {
521                 try {
522                     schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
523                     return false;
524                 } catch (InterruptedException | ExecutionException e) {
525                     return true;
526                 }
527             }).collect(Collectors.toList());
528         }
529
530         private Collection<SourceIdentifier> handleMissingSchemaSourceException(
531                 final MissingSchemaSourceException exception) {
532             // In case source missing, try without it
533             final SourceIdentifier missingSource = exception.getSourceId();
534             LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
535                 id, missingSource);
536             LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
537                 id, missingSource, exception);
538             final Collection<QName> qNameOfMissingSource =
539                 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
540             if (!qNameOfMissingSource.isEmpty()) {
541                 capabilities.addUnresolvedCapabilities(
542                         qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
543             }
544             return stripUnavailableSource(missingSource);
545         }
546
547         private Collection<SourceIdentifier> handleSchemaResolutionException(
548                 final SchemaResolutionException resolutionException) {
549             // In case resolution error, try only with resolved sources
550             // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
551             // FIXME Do we really have assurance that these two cases cannot happen at once?
552             if (resolutionException.getFailedSource() != null) {
553                 // flawed model - exclude it
554                 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
555                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
556                     id, failedSourceId);
557                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
558                     id, failedSourceId, resolutionException);
559                 capabilities.addUnresolvedCapabilities(
560                         getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
561                         UnavailableCapability.FailureReason.UnableToResolve);
562                 return stripUnavailableSource(resolutionException.getFailedSource());
563             }
564             // unsatisfied imports
565             final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
566             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
567                 UnavailableCapability.FailureReason.UnableToResolve);
568             LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
569                 id, resolutionException.getUnsatisfiedImports());
570             LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
571                 id, resolutionException.getUnsatisfiedImports(), resolutionException);
572             return resolutionException.getResolvedSources();
573         }
574
575         private Collection<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
576             final LinkedList<SourceIdentifier> sourceIdentifiers = new LinkedList<>(requiredSources);
577             checkState(sourceIdentifiers.remove(sourceIdToRemove),
578                     "%s: Trying to remove %s from %s failed", id, sourceIdToRemove, requiredSources);
579             return sourceIdentifiers;
580         }
581
582         private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
583             final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
584
585             if (qNames.isEmpty()) {
586                 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
587                         identifiers);
588             }
589             return Collections2.filter(qNames, Predicates.notNull());
590         }
591
592         private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
593             // Required sources are all required and provided merged in DeviceSourcesResolver
594             for (final QName qname : deviceSources.getRequiredSourcesQName()) {
595                 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
596                     continue;
597                 }
598
599                 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
600                     return qname;
601                 }
602             }
603             LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
604                     deviceSources.getRequiredSourcesQName());
605             // return null since we cannot find the QName,
606             // this capability will be removed from required sources and not reported as unresolved-capability
607             return null;
608         }
609     }
610 }