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