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