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