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