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