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