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