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