Merge "Add support for notification subtree filter"
[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.RemoteDevice;
36 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
37 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
38 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
39 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
40 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
41 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
42 import org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
43 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
44 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
45 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
51 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
52 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
53 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
54 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
55 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
56 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
57 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
58 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 /**
63  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
64  */
65 public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
66
67     private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
68
69     public static final Function<QName, SourceIdentifier> QNAME_TO_SOURCE_ID_FUNCTION = new Function<QName, SourceIdentifier>() {
70         @Override
71         public SourceIdentifier apply(final QName input) {
72             return new SourceIdentifier(input.getLocalName(), Optional.fromNullable(input.getFormattedRevision()));
73         }
74     };
75
76     protected final RemoteDeviceId id;
77     private final boolean reconnectOnSchemasChange;
78
79     protected final SchemaContextFactory schemaContextFactory;
80     private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
81     private final ListeningExecutorService processingExecutor;
82     protected final SchemaSourceRegistry schemaRegistry;
83     private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
84     private final NotificationHandler notificationHandler;
85     protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations = Lists.newArrayList();
86
87     // Message transformer is constructed once the schemas are available
88     private MessageTransformer<NetconfMessage> messageTransformer;
89
90     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
91                          final ExecutorService globalProcessingExecutor) {
92         this(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, false);
93     }
94
95     /**
96      * Create rpc implementation capable of handling RPC for monitoring and notifications even before the schemas of remote device are downloaded
97      */
98     static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, final boolean notificationSupport) {
99         NetconfMessageTransformer.BaseSchema baseSchema = notificationSupport ?
100                 NetconfMessageTransformer.BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
101                 NetconfMessageTransformer.BaseSchema.BASE_NETCONF_CTX;
102
103         return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener, new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
104     }
105
106
107     // FIXME reduce parameters
108     public 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(initRpc, 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         NetconfMessageTransformer.BaseSchema baseSchema =
201                 remoteSessionCapabilities.isNotificationsSupported() ?
202                 NetconfMessageTransformer.BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
203                 NetconfMessageTransformer.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 NetconfDeviceRpc deviceRpc, final DeviceSources deviceSources) {
233         final NetconfRemoteSchemaYangSourceProvider yangProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
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 NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
268
269         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry, final SchemaContextFactory schemaContextFactory, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver) {
270             this.schemaRegistry = Preconditions.checkNotNull(schemaRegistry);
271             this.schemaContextFactory = Preconditions.checkNotNull(schemaContextFactory);
272             this.stateSchemasResolver = Preconditions.checkNotNull(stateSchemasResolver);
273         }
274
275         public SchemaSourceRegistry getSchemaRegistry() {
276             return schemaRegistry;
277         }
278
279         public SchemaContextFactory getSchemaContextFactory() {
280             return schemaContextFactory;
281         }
282
283         public NetconfStateSchemas.NetconfStateSchemasResolver getStateSchemasResolver() {
284             return stateSchemasResolver;
285         }
286     }
287
288     /**
289      * Schema building callable.
290      */
291     private static class DeviceSourcesResolver implements Callable<DeviceSources> {
292
293         private final NetconfDeviceRpc deviceRpc;
294         private final NetconfSessionPreferences remoteSessionCapabilities;
295         private final RemoteDeviceId id;
296         private final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver;
297
298         DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities,
299                                      final RemoteDeviceId id, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver) {
300             this.deviceRpc = deviceRpc;
301             this.remoteSessionCapabilities = remoteSessionCapabilities;
302             this.id = id;
303             this.stateSchemasResolver = stateSchemasResolver;
304         }
305
306         public DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id, final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver, final NetconfDeviceRpc rpcForMonitoring) {
307             this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver);
308         }
309
310         @Override
311         public DeviceSources call() throws Exception {
312             final NetconfStateSchemas availableSchemas = stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
313             LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id, availableSchemas.getAvailableYangSchemasQNames());
314
315             final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
316             final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
317
318             final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
319             if (!requiredSourcesNotProvided.isEmpty()) {
320                 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}",
321                         id, requiredSourcesNotProvided);
322                 LOG.warn("{}: Attempting to build schema context from required sources", id);
323             }
324
325             // Here all the sources reported in netconf monitoring are merged with those reported in hello.
326             // It is necessary to perform this since submodules are not mentioned in hello but still required.
327             // This clashes with the option of a user to specify supported yang models manually in configuration for netconf-connector
328             // and as a result one is not able to fully override yang models of a device. It is only possible to add additional models.
329             final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
330             if (!providedSourcesNotRequired.isEmpty()) {
331                 LOG.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}",
332                         id, providedSourcesNotRequired);
333                 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
334                 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
335                 requiredSources.addAll(providedSourcesNotRequired);
336             }
337
338             return new DeviceSources(requiredSources, providedSources);
339         }
340     }
341
342     /**
343      * Contains RequiredSources - sources from capabilities.
344      */
345     private static final class DeviceSources {
346         private final Set<QName> requiredSources;
347         private final Set<QName> providedSources;
348
349         public DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources) {
350             this.requiredSources = requiredSources;
351             this.providedSources = providedSources;
352         }
353
354         public Set<QName> getRequiredSourcesQName() {
355             return requiredSources;
356         }
357
358         public Set<QName> getProvidedSourcesQName() {
359             return providedSources;
360         }
361
362         public Collection<SourceIdentifier> getRequiredSources() {
363             return Collections2.transform(requiredSources, QNAME_TO_SOURCE_ID_FUNCTION);
364         }
365
366         public Collection<SourceIdentifier> getProvidedSources() {
367             return Collections2.transform(providedSources, QNAME_TO_SOURCE_ID_FUNCTION);
368         }
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 Runnable {
376         private final DeviceSources deviceSources;
377         private final NetconfSessionPreferences remoteSessionCapabilities;
378         private final RemoteDeviceCommunicator<NetconfMessage> listener;
379         private final NetconfDeviceCapabilities capabilities;
380
381         public SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceCommunicator<NetconfMessage> listener) {
382             this.deviceSources = deviceSources;
383             this.remoteSessionCapabilities = remoteSessionCapabilities;
384             this.listener = listener;
385             this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
386         }
387
388         @Override
389         public void run() {
390             setUpSchema(deviceSources.getRequiredSources());
391         }
392
393         /**
394          * Build schema context, in case of success or final failure notify device
395          */
396         private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
397             while (!requiredSources.isEmpty()) {
398                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
399                 try {
400                     final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture = schemaContextFactory.createSchemaContext(requiredSources);
401                     final SchemaContext result = schemaBuilderFuture.checkedGet();
402                     LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
403                     final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), capabilities.getUnresolvedCapabilites().keySet());
404                     capabilities.addCapabilities(filteredQNames);
405                     capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps());
406                     handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
407                     return;
408                 } catch (Throwable t) {
409                     if (t instanceof MissingSchemaSourceException){
410                         // In case source missing, try without it
411                         final SourceIdentifier missingSource = ((MissingSchemaSourceException) t).getSourceId();
412                         LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
413                         LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", t);
414                         final Collection<QName> qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
415                         if (!qNameOfMissingSource.isEmpty()) {
416                             capabilities.addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
417                         }
418                         requiredSources = stripMissingSource(requiredSources, missingSource);
419                     } else if (t instanceof SchemaResolutionException) {
420                         // In case resolution error, try only with resolved sources
421                         SchemaResolutionException resolutionException = (SchemaResolutionException) t;
422                         final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
423                         capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
424                         LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
425                         LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", resolutionException);
426                         requiredSources = resolutionException.getResolvedSources();
427                     } else {
428                         // unknown error, fail
429                         handleSalInitializationFailure(t, listener);
430                         return;
431                     }
432                 }
433             }
434             // No more sources, fail
435             final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context");
436             handleSalInitializationFailure(cause, listener);
437             salFacade.onDeviceFailed(cause);
438         }
439
440
441         protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
442             return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
443         }
444
445         private Collection<SourceIdentifier> stripMissingSource(final Collection<SourceIdentifier> requiredSources, final SourceIdentifier sIdToRemove) {
446             final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
447             final boolean removed = sourceIdentifiers.remove(sIdToRemove);
448             Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources);
449             return sourceIdentifiers;
450         }
451
452         private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
453             final Collection<QName> qNames = Collections2.transform(identifiers, new Function<SourceIdentifier, QName>() {
454                 @Override
455                 public QName apply(final SourceIdentifier sourceIdentifier) {
456                     return getQNameFromSourceIdentifier(sourceIdentifier);
457                 }
458             });
459
460             if (qNames.isEmpty()) {
461                 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, identifiers);
462             }
463             return Collections2.filter(qNames, Predicates.notNull());
464         }
465
466         private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
467             // Required sources are all required and provided merged in DeviceSourcesResolver
468             for (final QName qname : deviceSources.getRequiredSourcesQName()) {
469                 if(qname.getLocalName().equals(identifier.getName()) == false) {
470                     continue;
471                 }
472
473                 if(identifier.getRevision().equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION) &&
474                         qname.getRevision() == null) {
475                     return qname;
476                 }
477
478                 if (qname.getFormattedRevision().equals(identifier.getRevision())) {
479                     return qname;
480                 }
481             }
482             LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier, deviceSources.getRequiredSourcesQName());
483             // return null since we cannot find the QName, this capability will be removed from required sources and not reported as unresolved-capability
484             return null;
485         }
486     }
487 }