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