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