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