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