0460b115cd11adb33144886bd4ae77c60f0389cf
[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.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231025.connection.oper.available.capabilities.AvailableCapability;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231025.connection.oper.available.capabilities.AvailableCapabilityBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231025.connection.oper.unavailable.capabilities.UnavailableCapability;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev231025.connection.oper.unavailable.capabilities.UnavailableCapability.FailureReason;
61 import org.opendaylight.yangtools.concepts.Registration;
62 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
63 import org.opendaylight.yangtools.yang.common.QName;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.schema.MountPointContext;
67 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
68 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
69 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
70 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
71 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
72 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
73 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
74 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
75 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78
79 /**
80  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
81  */
82 public class NetconfDevice implements RemoteDevice<NetconfDeviceCommunicator> {
83     private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
84
85     private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
86         SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
87     private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.of(
88         NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
89
90     protected final RemoteDeviceId id;
91     protected final EffectiveModelContextFactory schemaContextFactory;
92     protected final SchemaSourceRegistry schemaRegistry;
93     protected final SchemaRepository schemaRepository;
94
95     protected final List<Registration> sourceRegistrations = new ArrayList<>();
96
97     private final RemoteDeviceHandler salFacade;
98     private final Executor processingExecutor;
99     private final DeviceActionFactory deviceActionFactory;
100     private final NetconfDeviceSchemasResolver stateSchemasResolver;
101     private final NotificationHandler notificationHandler;
102     private final boolean reconnectOnSchemasChange;
103     private final BaseNetconfSchemas baseSchemas;
104
105     @GuardedBy("this")
106     private ListenableFuture<List<Object>> schemaFuturesList;
107     @GuardedBy("this")
108     private boolean connected = false;
109
110     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
111             final RemoteDeviceId id, final RemoteDeviceHandler salFacade, final Executor globalProcessingExecutor,
112             final boolean reconnectOnSchemasChange) {
113         this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
114     }
115
116     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
117             final RemoteDeviceId id, final RemoteDeviceHandler salFacade, final Executor globalProcessingExecutor,
118             final boolean reconnectOnSchemasChange, final DeviceActionFactory deviceActionFactory) {
119         this.baseSchemas = requireNonNull(baseSchemas);
120         this.id = id;
121         this.reconnectOnSchemasChange = reconnectOnSchemasChange;
122         this.deviceActionFactory = deviceActionFactory;
123         schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
124         schemaRepository = schemaResourcesDTO.getSchemaRepository();
125         schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
126         this.salFacade = salFacade;
127         stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
128         processingExecutor = requireNonNull(globalProcessingExecutor);
129         notificationHandler = new NotificationHandler(salFacade, id);
130     }
131
132     @Override
133     public synchronized void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
134             final NetconfDeviceCommunicator listener) {
135         // SchemaContext setup has to be performed in a dedicated thread since we are in a Netty thread in this method
136         // YANG models are being downloaded in this method and it would cause a deadlock if we used the netty thread
137         // https://netty.io/wiki/thread-model.html
138         setConnected(true);
139         LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
140
141         final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
142         final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
143             new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
144         final var sourceResolverFuture = Futures.submit(new DeviceSourcesResolver(id, baseSchema, initRpc,
145                 remoteSessionCapabilities, stateSchemasResolver), processingExecutor);
146
147         if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
148             registerToBaseNetconfStream(initRpc, listener);
149         }
150
151         // Set up the EffectiveModelContext for the device
152         final var futureSchema = Futures.transformAsync(sourceResolverFuture,
153             deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
154
155         // Potentially acquire mount point list and interpret it
156         final var netconfDeviceSchemaFuture = Futures.transformAsync(futureSchema,
157             result -> Futures.transform(createMountPointContext(result.modelContext(), baseSchema, listener),
158                 mount -> new NetconfDeviceSchema(result.capabilities(), mount), processingExecutor),
159             processingExecutor);
160         schemaFuturesList = Futures.allAsList(sourceResolverFuture, futureSchema, netconfDeviceSchemaFuture);
161
162         Futures.addCallback(netconfDeviceSchemaFuture, new FutureCallback<>() {
163                 @Override
164                 public void onSuccess(final NetconfDeviceSchema result) {
165                     handleSalInitializationSuccess(listener, result, remoteSessionCapabilities,
166                         getDeviceSpecificRpc(result.mountContext(), listener, baseSchema));
167                 }
168
169                 @Override
170                 public void onFailure(final Throwable cause) {
171                     // The method onRemoteSessionDown was called while the EffectiveModelContext for the device
172                     // was being processed.
173                     if (cause instanceof CancellationException) {
174                         LOG.warn("{}: Device communicator was tear down since the schema setup started", id);
175                     } else {
176                         handleSalInitializationFailure(listener, cause);
177                     }
178                 }
179             }, MoreExecutors.directExecutor());
180     }
181
182     private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
183                                              final NetconfDeviceCommunicator listener) {
184         // TODO check whether the model describing create subscription is present in schema
185         // Perhaps add a default schema context to support create-subscription if the model was not provided
186         // (same as what we do for base netconf operations in transformer)
187         final var rpcResultListenableFuture = deviceRpc.invokeRpc(
188                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
189                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
190
191         Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
192             @Override
193             public void onSuccess(final DOMRpcResult domRpcResult) {
194                 notificationHandler.addNotificationFilter(notification -> {
195                     if (NetconfCapabilityChange.QNAME.equals(notification.getBody().name().getNodeType())) {
196                         LOG.info("{}: Schemas change detected, reconnecting", id);
197                         // Only disconnect is enough,
198                         // the reconnecting nature of the connector will take care of reconnecting
199                         listener.disconnect();
200                         return false;
201                     }
202                     return true;
203                 });
204             }
205
206             @Override
207             public void onFailure(final Throwable throwable) {
208                 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
209                         throwable);
210             }
211         }, MoreExecutors.directExecutor());
212     }
213
214     private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
215         return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
216     }
217
218     private synchronized void handleSalInitializationSuccess(final RemoteDeviceCommunicator listener,
219             final NetconfDeviceSchema deviceSchema, final NetconfSessionPreferences remoteSessionCapabilities,
220             final Rpcs deviceRpc) {
221         // NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
222         // since salFacade.onDeviceDisconnected was already called.
223         if (!connected) {
224             LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
225             return;
226         }
227
228         final var messageTransformer = new NetconfMessageTransformer(deviceSchema.mountContext(), true,
229             resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
230
231         // Order is important here: salFacade has to see the device come up and then the notificationHandler can deliver
232         // whatever notifications have been held back
233         salFacade.onDeviceConnected(deviceSchema, remoteSessionCapabilities,
234             new RemoteDeviceServices(deviceRpc, deviceActionFactory == null ? null
235                 : deviceActionFactory.createDeviceAction(messageTransformer, listener)));
236         notificationHandler.onRemoteSchemaUp(messageTransformer);
237
238         LOG.info("{}: Netconf connector initialized successfully", id);
239     }
240
241     private void handleSalInitializationFailure(final RemoteDeviceCommunicator listener, final Throwable cause) {
242         LOG.warn("{}: Unexpected error resolving device sources", id, cause);
243         listener.close();
244         cleanupInitialization();
245         salFacade.onDeviceFailed(cause);
246     }
247
248     private synchronized void cleanupInitialization() {
249         connected = false;
250         if (schemaFuturesList != null && !schemaFuturesList.isDone()) {
251             if (!schemaFuturesList.cancel(true)) {
252                 LOG.warn("The cleanup of Schema Futures for device {} was unsuccessful.", id);
253             }
254         }
255         notificationHandler.onRemoteSchemaDown();
256         sourceRegistrations.forEach(Registration::close);
257         sourceRegistrations.clear();
258     }
259
260     private synchronized void setConnected(final boolean connected) {
261         this.connected = connected;
262     }
263
264     private ListenableFuture<SchemaResult> assembleSchemaContext(final DeviceSources deviceSources,
265             final NetconfSessionPreferences remoteSessionCapabilities) {
266         LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
267
268         sourceRegistrations.addAll(deviceSources.register(schemaRegistry));
269
270         return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
271     }
272
273     private ListenableFuture<@NonNull MountPointContext> createMountPointContext(
274             final EffectiveModelContext schemaContext, final BaseSchema baseSchema,
275             final NetconfDeviceCommunicator listener) {
276         final MountPointContext emptyContext = MountPointContext.of(schemaContext);
277         if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
278             return Futures.immediateFuture(emptyContext);
279         }
280
281         // Create a temporary RPC invoker and acquire the mount point tree
282         LOG.debug("{}: Acquiring available mount points", id);
283         final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
284             new NetconfMessageTransformer(emptyContext, false, baseSchema));
285
286         return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
287             Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
288                 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
289                 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
290     }
291
292     private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
293         final var errors = rpcResult.errors();
294         if (!errors.isEmpty()) {
295             LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
296         }
297         final var schemaMounts = rpcResult.value();
298         if (schemaMounts == null) {
299             LOG.debug("{}: device does not define any schema mounts", id);
300             return emptyContext;
301         }
302
303         return DeviceMountPointContext.create(emptyContext, schemaMounts);
304     }
305
306     @Override
307     public void onRemoteSessionDown() {
308         cleanupInitialization();
309         salFacade.onDeviceDisconnected();
310     }
311
312     @Override
313     public void onNotification(final NetconfMessage notification) {
314         notificationHandler.handleNotification(notification);
315     }
316
317     private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
318         return notificationSupport ? baseSchemas.baseSchemaWithNotifications() : baseSchemas.baseSchema();
319     }
320
321     protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
322             final RemoteDeviceCommunicator listener, final BaseSchema schema) {
323         return new NetconfDeviceRpc(result.getEffectiveModelContext(), 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.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
412                         .$YangModuleInfoImpl.getInstance().getName(),
413                     org.opendaylight.yang.gen.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, YangTextSchemaSource.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.getSourceId();
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             if (resolutionException.getFailedSource() != null) {
525                 // flawed model - exclude it
526                 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
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(resolutionException.getFailedSource());
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 }