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