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