3caa773c960afff5853113b7a5dfce3ea6a7a89a
[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.BaseNetconfSchema;
43 import org.opendaylight.netconf.client.mdsal.api.BaseNetconfSchemaProvider;
44 import org.opendaylight.netconf.client.mdsal.api.DeviceActionFactory;
45 import org.opendaylight.netconf.client.mdsal.api.NetconfDeviceSchemasResolver;
46 import org.opendaylight.netconf.client.mdsal.api.NetconfSessionPreferences;
47 import org.opendaylight.netconf.client.mdsal.api.RemoteDevice;
48 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceCommunicator;
49 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceHandler;
50 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
51 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices;
52 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices.Rpcs;
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.spi.node.ImmutableNodes;
71 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
72 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
73 import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
74 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
75 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
76 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
77 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
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 BaseNetconfSchemaProvider 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 BaseNetconfSchemaProvider 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 BaseNetconfSchemaProvider 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 var baseSchema = baseSchemas.baseSchemaForCapabilities(remoteSessionCapabilities);
145         final var initRpc = new NetconfDeviceRpc(baseSchema.modelContext(), listener,
146             new NetconfMessageTransformer(baseSchema.mountPointContext(), 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, baseSchema, 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, ImmutableNodes.newContainerBuilder()
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 BaseNetconfSchema baseSchema, final NetconfDeviceSchema deviceSchema,
225             final NetconfSessionPreferences remoteSessionCapabilities, 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, baseSchema);
234
235         // Order is important here: salFacade has to see the device come up and then the notificationHandler can deliver
236         // whatever notifications have been held back
237         salFacade.onDeviceConnected(deviceSchema, remoteSessionCapabilities,
238             new RemoteDeviceServices(deviceRpc, deviceActionFactory == null ? null
239                 : deviceActionFactory.createDeviceAction(messageTransformer, listener)));
240         notificationHandler.onRemoteSchemaUp(messageTransformer);
241
242         LOG.info("{}: Netconf connector initialized successfully", id);
243     }
244
245     private void handleSalInitializationFailure(final RemoteDeviceCommunicator listener, final Throwable cause) {
246         LOG.warn("{}: Unexpected error resolving device sources", id, cause);
247         listener.close();
248         cleanupInitialization();
249         salFacade.onDeviceFailed(cause);
250     }
251
252     private synchronized void cleanupInitialization() {
253         connected = false;
254         if (schemaFuturesList != null && !schemaFuturesList.isDone()) {
255             if (!schemaFuturesList.cancel(true)) {
256                 LOG.warn("The cleanup of Schema Futures for device {} was unsuccessful.", id);
257             }
258         }
259         notificationHandler.onRemoteSchemaDown();
260         sourceRegistrations.forEach(Registration::close);
261         sourceRegistrations.clear();
262     }
263
264     private synchronized void setConnected(final boolean connected) {
265         this.connected = connected;
266     }
267
268     private ListenableFuture<SchemaResult> assembleSchemaContext(final DeviceSources deviceSources,
269             final NetconfSessionPreferences remoteSessionCapabilities) {
270         LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
271
272         sourceRegistrations.addAll(deviceSources.register(schemaRegistry));
273
274         return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
275     }
276
277     private ListenableFuture<@NonNull MountPointContext> createMountPointContext(
278             final EffectiveModelContext schemaContext, final BaseNetconfSchema baseSchema,
279             final NetconfDeviceCommunicator listener) {
280         final MountPointContext emptyContext = MountPointContext.of(schemaContext);
281         if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
282             return Futures.immediateFuture(emptyContext);
283         }
284
285         // Create a temporary RPC invoker and acquire the mount point tree
286         LOG.debug("{}: Acquiring available mount points", id);
287         final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
288             new NetconfMessageTransformer(emptyContext, false, baseSchema));
289
290         return Futures.transform(deviceRpc.domRpcService().invokeRpc(Get.QNAME, ImmutableNodes.newContainerBuilder()
291             .withNodeIdentifier(NETCONF_GET_NODEID)
292             .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
293             .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
294     }
295
296     private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
297         final var errors = rpcResult.errors();
298         if (!errors.isEmpty()) {
299             LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
300         }
301         final var schemaMounts = rpcResult.value();
302         if (schemaMounts == null) {
303             LOG.debug("{}: device does not define any schema mounts", id);
304             return emptyContext;
305         }
306
307         return DeviceMountPointContext.create(emptyContext, schemaMounts);
308     }
309
310     @Override
311     public void onRemoteSessionDown() {
312         cleanupInitialization();
313         salFacade.onDeviceDisconnected();
314     }
315
316     @Override
317     public void onNotification(final NetconfMessage notification) {
318         notificationHandler.handleNotification(notification);
319     }
320
321     protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
322             final RemoteDeviceCommunicator listener, final BaseNetconfSchema schema) {
323         return new NetconfDeviceRpc(result.modelContext(), listener,
324             new NetconfMessageTransformer(result, true, schema));
325     }
326
327     /**
328      * Just a transfer object containing schema related dependencies. Injected in constructor.
329      */
330     public static class SchemaResourcesDTO {
331         private final SchemaSourceRegistry schemaRegistry;
332         private final SchemaRepository schemaRepository;
333         private final EffectiveModelContextFactory schemaContextFactory;
334         private final NetconfDeviceSchemasResolver stateSchemasResolver;
335
336         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
337                                   final SchemaRepository schemaRepository,
338                                   final EffectiveModelContextFactory schemaContextFactory,
339                                   final NetconfDeviceSchemasResolver deviceSchemasResolver) {
340             this.schemaRegistry = requireNonNull(schemaRegistry);
341             this.schemaRepository = requireNonNull(schemaRepository);
342             this.schemaContextFactory = requireNonNull(schemaContextFactory);
343             stateSchemasResolver = requireNonNull(deviceSchemasResolver);
344         }
345
346         public SchemaSourceRegistry getSchemaRegistry() {
347             return schemaRegistry;
348         }
349
350         public SchemaRepository getSchemaRepository() {
351             return schemaRepository;
352         }
353
354         public EffectiveModelContextFactory getSchemaContextFactory() {
355             return schemaContextFactory;
356         }
357
358         public NetconfDeviceSchemasResolver getStateSchemasResolver() {
359             return stateSchemasResolver;
360         }
361     }
362
363     /**
364      * A dedicated exception to indicate when we fail to setup an {@link EffectiveModelContext}.
365      */
366     public static final class EmptySchemaContextException extends Exception {
367         @Serial
368         private static final long serialVersionUID = 1L;
369
370         public EmptySchemaContextException(final String message) {
371             super(message);
372         }
373     }
374
375     /**
376      * {@link NetconfDeviceCapabilities} and {@link EffectiveModelContext}.
377      */
378     private record SchemaResult(
379         @NonNull NetconfDeviceCapabilities capabilities,
380         @NonNull EffectiveModelContext modelContext) {
381
382         SchemaResult {
383             requireNonNull(capabilities);
384             requireNonNull(modelContext);
385         }
386     }
387
388     /**
389      * Schema builder that tries to build schema context from provided sources or biggest subset of it.
390      */
391     private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
392         private final SettableFuture<SchemaResult> resultFuture = SettableFuture.create();
393
394         private final Set<AvailableCapability> nonModuleBasedCapabilities = new HashSet<>();
395         private final Map<QName, FailureReason> unresolvedCapabilites = new HashMap<>();
396         private final Set<AvailableCapability> resolvedCapabilities = new HashSet<>();
397
398         private final DeviceSources deviceSources;
399         private final NetconfSessionPreferences remoteSessionCapabilities;
400
401         private Collection<SourceIdentifier> requiredSources;
402
403         SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
404             this.deviceSources = deviceSources;
405             this.remoteSessionCapabilities = remoteSessionCapabilities;
406
407             // If device supports notifications and does not contain necessary modules, add them automatically
408             if (remoteSessionCapabilities.containsNonModuleCapability(CapabilityURN.NOTIFICATION)) {
409                 // FIXME: mutable collection modification!
410                 deviceSources.getRequiredSourcesQName().addAll(List.of(
411                     org.opendaylight.yang.svc.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
412                         .YangModuleInfoImpl.getInstance().getName(),
413                     org.opendaylight.yang.svc.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
414                         .YangModuleInfoImpl.getInstance().getName())
415                 );
416             }
417
418             requiredSources = deviceSources.getRequiredSources();
419             final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
420
421             addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
422                 UnavailableCapability.FailureReason.MissingSource);
423             requiredSources.removeAll(missingSources);
424         }
425
426         ListenableFuture<SchemaResult> startResolution() {
427             trySetupSchema();
428             return resultFuture;
429         }
430
431         @Override
432         public void onSuccess(final EffectiveModelContext result) {
433             LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
434
435             final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
436                     unresolvedCapabilites.keySet());
437             resolvedCapabilities.addAll(filteredQNames.stream()
438                 .map(capability -> new AvailableCapabilityBuilder()
439                     .setCapability(capability.toString())
440                     .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
441                     .build())
442                 .collect(Collectors.toList()));
443
444             nonModuleBasedCapabilities.addAll(remoteSessionCapabilities.nonModuleCaps().keySet().stream()
445                 .map(capability -> new AvailableCapabilityBuilder()
446                     .setCapability(capability)
447                     .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
448                     .build())
449                 .collect(Collectors.toList()));
450
451
452             resultFuture.set(new SchemaResult(new NetconfDeviceCapabilities(ImmutableMap.copyOf(unresolvedCapabilites),
453                 ImmutableSet.copyOf(resolvedCapabilities), ImmutableSet.copyOf(nonModuleBasedCapabilities)), result));
454         }
455
456         @Override
457         public void onFailure(final Throwable cause) {
458             // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
459             // that might be wrapping a MissingSchemaSourceException so we need to look
460             // at the cause of the exception to make sure we don't misinterpret it.
461             if (cause instanceof MissingSchemaSourceException) {
462                 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
463             } else if (cause instanceof SchemaResolutionException) {
464                 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
465             } else {
466                 LOG.debug("Unhandled failure", cause);
467                 resultFuture.setException(cause);
468                 // No more trying...
469                 return;
470             }
471
472             trySetupSchema();
473         }
474
475         private void trySetupSchema() {
476             if (!requiredSources.isEmpty()) {
477                 // Initiate async resolution, drive it back based on the result
478                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
479                 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
480                     MoreExecutors.directExecutor());
481             } else {
482                 LOG.debug("{}: no more sources for schema context", id);
483                 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
484             }
485         }
486
487         private List<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
488             return origSources.parallelStream().filter(sourceIdentifier -> {
489                 try {
490                     schemaRepository.getSchemaSource(sourceIdentifier, YangTextSource.class).get();
491                     return false;
492                 } catch (InterruptedException | ExecutionException e) {
493                     return true;
494                 }
495             }).collect(Collectors.toList());
496         }
497
498         private void addUnresolvedCapabilities(final Collection<QName> capabilities, final FailureReason reason) {
499             for (QName s : capabilities) {
500                 unresolvedCapabilites.put(s, reason);
501             }
502         }
503
504         private List<SourceIdentifier> handleMissingSchemaSourceException(
505                 final MissingSchemaSourceException exception) {
506             // In case source missing, try without it
507             final SourceIdentifier missingSource = exception.sourceId();
508             LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
509                 id, missingSource);
510             LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
511                 id, missingSource, exception);
512             final var qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
513             if (!qNameOfMissingSource.isEmpty()) {
514                 addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
515             }
516             return stripUnavailableSource(missingSource);
517         }
518
519         private Collection<SourceIdentifier> handleSchemaResolutionException(
520                 final SchemaResolutionException resolutionException) {
521             // In case resolution error, try only with resolved sources
522             // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
523             // FIXME Do we really have assurance that these two cases cannot happen at once?
524             final var failedSourceId = resolutionException.sourceId();
525             if (failedSourceId != null) {
526                 // flawed model - exclude it
527                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
528                     id, failedSourceId);
529                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
530                     id, failedSourceId, resolutionException);
531                 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(List.of(failedSourceId)),
532                         UnavailableCapability.FailureReason.UnableToResolve);
533                 return stripUnavailableSource(failedSourceId);
534             }
535             // unsatisfied imports
536             addUnresolvedCapabilities(
537                 getQNameFromSourceIdentifiers(resolutionException.getUnsatisfiedImports().keySet()),
538                 UnavailableCapability.FailureReason.UnableToResolve);
539             LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
540                 id, resolutionException.getUnsatisfiedImports());
541             LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
542                 id, resolutionException.getUnsatisfiedImports(), resolutionException);
543             return resolutionException.getResolvedSources();
544         }
545
546         private List<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
547             final var tmp = new ArrayList<>(requiredSources);
548             checkState(tmp.remove(sourceIdToRemove), "%s: Trying to remove %s from %s failed", id, sourceIdToRemove,
549                 requiredSources);
550             return tmp;
551         }
552
553         private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
554             final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
555
556             if (qNames.isEmpty()) {
557                 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
558                         identifiers);
559             }
560             return Collections2.filter(qNames, Predicates.notNull());
561         }
562
563         private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
564             // Required sources are all required and provided merged in DeviceSourcesResolver
565             for (final QName qname : deviceSources.getRequiredSourcesQName()) {
566                 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
567                     continue;
568                 }
569
570                 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
571                     return qname;
572                 }
573             }
574             LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
575                     deviceSources.getRequiredSourcesQName());
576             // return null since we cannot find the QName,
577             // this capability will be removed from required sources and not reported as unresolved-capability
578             return null;
579         }
580     }
581 }