69efd2858e4f681f21ec5fbf8dbd46460df6443f
[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 com.google.common.base.Function;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicates;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Sets;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.ListeningExecutorService;
22 import com.google.common.util.concurrent.MoreExecutors;
23 import java.util.Collection;
24 import java.util.LinkedList;
25 import java.util.List;
26 import java.util.Set;
27 import java.util.concurrent.Callable;
28 import java.util.concurrent.ExecutorService;
29 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
30 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
31 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
33 import org.opendaylight.netconf.api.NetconfMessage;
34 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
35 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
36 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
37 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
38 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
39 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
40 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
41 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
42 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
43 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
44 import org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
45 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
46 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
47 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
48 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
49 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
54 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
55 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
56 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
57 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
58 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
59 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
60 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
61 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
62 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
63 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
64 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67
68 /**
69  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
70  */
71 public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
72
73     private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
74
75     public static final Function<QName, SourceIdentifier> QNAME_TO_SOURCE_ID_FUNCTION = new Function<QName, SourceIdentifier>() {
76         @Override
77         public SourceIdentifier apply(final QName input) {
78             return RevisionSourceIdentifier
79                     .create(input.getLocalName(), Optional.fromNullable(input.getFormattedRevision()));
80         }
81     };
82
83     protected final RemoteDeviceId id;
84     private final boolean reconnectOnSchemasChange;
85
86     protected final SchemaContextFactory schemaContextFactory;
87     private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
88     private final ListeningExecutorService processingExecutor;
89     protected final SchemaSourceRegistry schemaRegistry;
90     private final NetconfDeviceSchemasResolver stateSchemasResolver;
91     private final NotificationHandler notificationHandler;
92     protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations = Lists.newArrayList();
93
94     // Message transformer is constructed once the schemas are available
95     private MessageTransformer<NetconfMessage> messageTransformer;
96
97     /**
98      * Create rpc implementation capable of handling RPC for monitoring and notifications even before the schemas of remote device are downloaded
99      */
100     static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, final boolean notificationSupport) {
101         final BaseSchema baseSchema = notificationSupport ?
102                 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
103                 BaseSchema.BASE_NETCONF_CTX;
104
105         return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener, new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
106     }
107
108     protected NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
109                          final ExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
110         this.id = id;
111         this.reconnectOnSchemasChange = reconnectOnSchemasChange;
112         this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
113         this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
114         this.salFacade = salFacade;
115         this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
116         this.processingExecutor = MoreExecutors.listeningDecorator(globalProcessingExecutor);
117         this.notificationHandler = new NotificationHandler(salFacade, id);
118     }
119
120     @Override
121     public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
122                                   final NetconfDeviceCommunicator listener) {
123         // SchemaContext setup has to be performed in a dedicated thread since
124         // we are in a netty thread in this method
125         // Yang models are being downloaded in this method and it would cause a
126         // deadlock if we used the netty thread
127         // http://netty.io/wiki/thread-model.html
128         LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
129
130         final NetconfDeviceRpc initRpc = getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
131         final DeviceSourcesResolver task = new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
132         final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
133
134         if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
135             registerToBaseNetconfStream(initRpc, listener);
136         }
137
138         final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
139             @Override
140             public void onSuccess(final DeviceSources result) {
141                 addProvidedSourcesToSchemaRegistry(result);
142                 setUpSchema(result);
143             }
144
145             private void setUpSchema(final DeviceSources result) {
146                 processingExecutor.submit(new SchemaSetup(result, remoteSessionCapabilities, listener));
147             }
148
149             @Override
150             public void onFailure(final Throwable t) {
151                 LOG.warn("{}: Unexpected error resolving device sources: {}", id, t);
152                 handleSalInitializationFailure(t, listener);
153             }
154         };
155
156         Futures.addCallback(sourceResolverFuture, resolvedSourceCallback);
157     }
158
159     private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc, final NetconfDeviceCommunicator listener) {
160        // TODO check whether the model describing create subscription is present in schema
161         // Perhaps add a default schema context to support create-subscription if the model was not provided (same as what we do for base netconf operations in transformer)
162         final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultListenableFuture =
163                 deviceRpc.invokeRpc(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME), NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
164
165         final NotificationHandler.NotificationFilter filter = new NotificationHandler.NotificationFilter() {
166             @Override
167             public Optional<DOMNotification> filterNotification(final DOMNotification notification) {
168                 if (isCapabilityChanged(notification)) {
169                     LOG.info("{}: Schemas change detected, reconnecting", id);
170                     // Only disconnect is enough, the reconnecting nature of the connector will take care of reconnecting
171                     listener.disconnect();
172                     return Optional.absent();
173                 }
174                 return Optional.of(notification);
175             }
176
177             private boolean isCapabilityChanged(final DOMNotification notification) {
178                 return notification.getBody().getNodeType().equals(NetconfCapabilityChange.QNAME);
179             }
180         };
181
182         Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
183             @Override
184             public void onSuccess(final DOMRpcResult domRpcResult) {
185                 notificationHandler.addNotificationFilter(filter);
186             }
187
188             @Override
189             public void onFailure(final Throwable t) {
190                 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly", t);
191             }
192         });
193     }
194
195     private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
196         return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
197     }
198
199     protected void handleSalInitializationSuccess(final SchemaContext result, final NetconfSessionPreferences remoteSessionCapabilities, final DOMRpcService deviceRpc) {
200         final BaseSchema baseSchema =
201                 remoteSessionCapabilities.isNotificationsSupported() ?
202                 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
203                 BaseSchema.BASE_NETCONF_CTX;
204         messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
205
206         updateTransformer(messageTransformer);
207         // salFacade.onDeviceConnected has to be called before the notification handler is initialized
208         salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc);
209         notificationHandler.onRemoteSchemaUp(messageTransformer);
210
211         LOG.info("{}: Netconf connector initialized successfully", id);
212     }
213
214     protected void handleSalInitializationFailure(final Throwable t, final RemoteDeviceCommunicator<NetconfMessage> listener) {
215         LOG.error("{}: Initialization in sal failed, disconnecting from device", id, t);
216         listener.close();
217         onRemoteSessionDown();
218         resetMessageTransformer();
219     }
220
221     /**
222      * Set the transformer to null as is in initial state
223      */
224     private void resetMessageTransformer() {
225         updateTransformer(null);
226     }
227
228     private void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
229         messageTransformer = transformer;
230     }
231
232     private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
233         final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
234         for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
235             sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
236                     PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
237         }
238     }
239
240     @Override
241     public void onRemoteSessionDown() {
242         notificationHandler.onRemoteSchemaDown();
243
244         salFacade.onDeviceDisconnected();
245         for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration : sourceRegistrations) {
246             sourceRegistration.close();
247         }
248         resetMessageTransformer();
249     }
250
251     @Override
252     public void onRemoteSessionFailed(final Throwable throwable) {
253         salFacade.onDeviceFailed(throwable);
254     }
255
256     @Override
257     public void onNotification(final NetconfMessage notification) {
258         notificationHandler.handleNotification(notification);
259     }
260
261     /**
262      * Just a transfer object containing schema related dependencies. Injected in constructor.
263      */
264     public static class SchemaResourcesDTO {
265         private final SchemaSourceRegistry schemaRegistry;
266         private final SchemaContextFactory schemaContextFactory;
267         private final NetconfDeviceSchemasResolver stateSchemasResolver;
268
269         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
270                                   final SchemaContextFactory schemaContextFactory,
271                                   final NetconfDeviceSchemasResolver deviceSchemasResolver) {
272             this.schemaRegistry = Preconditions.checkNotNull(schemaRegistry);
273             this.schemaContextFactory = Preconditions.checkNotNull(schemaContextFactory);
274             this.stateSchemasResolver = Preconditions.checkNotNull(deviceSchemasResolver);
275         }
276
277         public SchemaSourceRegistry getSchemaRegistry() {
278             return schemaRegistry;
279         }
280
281         public SchemaContextFactory getSchemaContextFactory() {
282             return schemaContextFactory;
283         }
284
285         public NetconfDeviceSchemasResolver getStateSchemasResolver() {
286             return stateSchemasResolver;
287         }
288     }
289
290     /**
291      * Schema building callable.
292      */
293     private static class DeviceSourcesResolver implements Callable<DeviceSources> {
294
295         private final NetconfDeviceRpc deviceRpc;
296         private final NetconfSessionPreferences remoteSessionCapabilities;
297         private final RemoteDeviceId id;
298         private final NetconfDeviceSchemasResolver stateSchemasResolver;
299
300         DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities,
301                                      final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver) {
302             this.deviceRpc = deviceRpc;
303             this.remoteSessionCapabilities = remoteSessionCapabilities;
304             this.id = id;
305             this.stateSchemasResolver = stateSchemasResolver;
306         }
307
308         public DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver, final NetconfDeviceRpc rpcForMonitoring) {
309             this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver);
310         }
311
312         @Override
313         public DeviceSources call() throws Exception {
314             final NetconfDeviceSchemas availableSchemas = stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
315             LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id, availableSchemas.getAvailableYangSchemasQNames());
316
317             final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
318             final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
319
320             final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
321             if (!requiredSourcesNotProvided.isEmpty()) {
322                 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}",
323                         id, requiredSourcesNotProvided);
324                 LOG.warn("{}: Attempting to build schema context from required sources", id);
325             }
326
327             // Here all the sources reported in netconf monitoring are merged with those reported in hello.
328             // It is necessary to perform this since submodules are not mentioned in hello but still required.
329             // This clashes with the option of a user to specify supported yang models manually in configuration for netconf-connector
330             // and as a result one is not able to fully override yang models of a device. It is only possible to add additional models.
331             final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
332             if (!providedSourcesNotRequired.isEmpty()) {
333                 LOG.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}",
334                         id, providedSourcesNotRequired);
335                 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
336                 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
337                 requiredSources.addAll(providedSourcesNotRequired);
338             }
339
340             final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
341             if(availableSchemas instanceof LibraryModulesSchemas) {
342                 sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
343                         ((LibraryModulesSchemas) availableSchemas).getAvailableModels());
344             } else {
345                 sourceProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
346             }
347
348             return new DeviceSources(requiredSources, providedSources, sourceProvider);
349         }
350     }
351
352     /**
353      * Contains RequiredSources - sources from capabilities.
354      */
355     private static final class DeviceSources {
356         private final Set<QName> requiredSources;
357         private final Set<QName> providedSources;
358         private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
359
360         public DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
361                              final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
362             this.requiredSources = requiredSources;
363             this.providedSources = providedSources;
364             this.sourceProvider = sourceProvider;
365         }
366
367         public Set<QName> getRequiredSourcesQName() {
368             return requiredSources;
369         }
370
371         public Set<QName> getProvidedSourcesQName() {
372             return providedSources;
373         }
374
375         public Collection<SourceIdentifier> getRequiredSources() {
376             return Collections2.transform(requiredSources, QNAME_TO_SOURCE_ID_FUNCTION);
377         }
378
379         public Collection<SourceIdentifier> getProvidedSources() {
380             return Collections2.transform(providedSources, QNAME_TO_SOURCE_ID_FUNCTION);
381         }
382
383         public SchemaSourceProvider<YangTextSchemaSource> getSourceProvider() {
384             return sourceProvider;
385         }
386     }
387
388     /**
389      * Schema builder that tries to build schema context from provided sources or biggest subset of it.
390      */
391     private final class SchemaSetup implements Runnable {
392         private final DeviceSources deviceSources;
393         private final NetconfSessionPreferences remoteSessionCapabilities;
394         private final RemoteDeviceCommunicator<NetconfMessage> listener;
395         private final NetconfDeviceCapabilities capabilities;
396
397         public SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceCommunicator<NetconfMessage> listener) {
398             this.deviceSources = deviceSources;
399             this.remoteSessionCapabilities = remoteSessionCapabilities;
400             this.listener = listener;
401             this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
402         }
403
404         @Override
405         public void run() {
406             setUpSchema(deviceSources.getRequiredSources());
407         }
408
409         /**
410          * Build schema context, in case of success or final failure notify device
411          */
412         private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
413             while (!requiredSources.isEmpty()) {
414                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
415                 try {
416                     final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture = schemaContextFactory.createSchemaContext(requiredSources);
417                     final SchemaContext result = schemaBuilderFuture.checkedGet();
418                     LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
419                     final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), capabilities.getUnresolvedCapabilites().keySet());
420                     capabilities.addCapabilities(filteredQNames);
421                     capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps());
422                     handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
423                     return;
424                 } catch (final Throwable t) {
425                     if (t instanceof MissingSchemaSourceException){
426                         requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t);
427                     } else if (t instanceof SchemaResolutionException) {
428                         // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
429                         // that might be wrapping a MissingSchemaSourceException so we need to look
430                         // at the cause of the exception to make sure we don't misinterpret it.
431                         if (t.getCause() instanceof MissingSchemaSourceException) {
432                             requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t.getCause());
433                             continue;
434                         }
435                         requiredSources = handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t);
436                     } else {
437                         // unknown error, fail
438                         handleSalInitializationFailure(t, listener);
439                         return;
440                     }
441                 }
442             }
443             // No more sources, fail
444             final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context");
445             handleSalInitializationFailure(cause, listener);
446             salFacade.onDeviceFailed(cause);
447         }
448
449         private Collection<SourceIdentifier> handleMissingSchemaSourceException(final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException t) {
450             // In case source missing, try without it
451             final SourceIdentifier missingSource = t.getSourceId();
452             LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
453             LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", t);
454             final Collection<QName> qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
455             if (!qNameOfMissingSource.isEmpty()) {
456                 capabilities.addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
457             }
458             return stripMissingSource(requiredSources, missingSource);
459         }
460
461         private Collection<SourceIdentifier> handleSchemaResolutionException(final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
462             // In case resolution error, try only with resolved sources
463             final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
464             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
465             LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
466             LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", resolutionException);
467             return resolutionException.getResolvedSources();
468         }
469
470         protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
471             return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
472         }
473
474         private Collection<SourceIdentifier> stripMissingSource(final Collection<SourceIdentifier> requiredSources, final SourceIdentifier sIdToRemove) {
475             final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
476             final boolean removed = sourceIdentifiers.remove(sIdToRemove);
477             Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources);
478             return sourceIdentifiers;
479         }
480
481         private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
482             final Collection<QName> qNames = Collections2.transform(identifiers, new Function<SourceIdentifier, QName>() {
483                 @Override
484                 public QName apply(final SourceIdentifier sourceIdentifier) {
485                     return getQNameFromSourceIdentifier(sourceIdentifier);
486                 }
487             });
488
489             if (qNames.isEmpty()) {
490                 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, identifiers);
491             }
492             return Collections2.filter(qNames, Predicates.notNull());
493         }
494
495         private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
496             // Required sources are all required and provided merged in DeviceSourcesResolver
497             for (final QName qname : deviceSources.getRequiredSourcesQName()) {
498                 if(qname.getLocalName().equals(identifier.getName()) == false) {
499                     continue;
500                 }
501
502                 if(identifier.getRevision().equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION) &&
503                         qname.getRevision() == null) {
504                     return qname;
505                 }
506
507                 if (qname.getFormattedRevision().equals(identifier.getRevision())) {
508                     return qname;
509                 }
510             }
511             LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier, deviceSources.getRequiredSourcesQName());
512             // return null since we cannot find the QName, this capability will be removed from required sources and not reported as unresolved-capability
513             return null;
514         }
515     }
516 }