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