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