BUG-7850: SourceIdentifier.getRevision() can return null
[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.AvailableCapability;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
58 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
59 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
60 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
61 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
65 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
66 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
67 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
68 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
69 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
70 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
71 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75 /**
76  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
77  */
78 public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
79
80     private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
81
82     public static final Function<QName, SourceIdentifier> QNAME_TO_SOURCE_ID_FUNCTION =
83             input -> RevisionSourceIdentifier.create(input.getLocalName(),
84                 Optional.fromNullable(input.getFormattedRevision()));
85
86     protected final RemoteDeviceId id;
87     private final boolean reconnectOnSchemasChange;
88
89     protected final SchemaContextFactory schemaContextFactory;
90     private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
91     private final ListeningExecutorService processingExecutor;
92     protected final SchemaSourceRegistry schemaRegistry;
93     protected final SchemaRepository schemaRepository;
94     private final NetconfDeviceSchemasResolver stateSchemasResolver;
95     private final NotificationHandler notificationHandler;
96     protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations = Lists.newArrayList();
97
98     // Message transformer is constructed once the schemas are available
99     private MessageTransformer<NetconfMessage> messageTransformer;
100
101     /**
102      * Create rpc implementation capable of handling RPC for monitoring and notifications even before the schemas of remote device are downloaded
103      */
104     static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, final boolean notificationSupport) {
105         final BaseSchema baseSchema = notificationSupport ?
106                 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
107                 BaseSchema.BASE_NETCONF_CTX;
108
109         return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener, new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
110     }
111
112     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
113                          final ExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
114         this.id = id;
115         this.reconnectOnSchemasChange = reconnectOnSchemasChange;
116         this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
117         this.schemaRepository = schemaResourcesDTO.getSchemaRepository();
118         this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
119         this.salFacade = salFacade;
120         this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
121         this.processingExecutor = MoreExecutors.listeningDecorator(globalProcessingExecutor);
122         this.notificationHandler = new NotificationHandler(salFacade, id);
123     }
124
125     @Override
126     public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
127                                   final NetconfDeviceCommunicator listener) {
128         // SchemaContext setup has to be performed in a dedicated thread since
129         // we are in a netty thread in this method
130         // Yang models are being downloaded in this method and it would cause a
131         // deadlock if we used the netty thread
132         // http://netty.io/wiki/thread-model.html
133         LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
134
135         final NetconfDeviceRpc initRpc = getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
136         final DeviceSourcesResolver task = new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
137         final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
138
139         if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
140             registerToBaseNetconfStream(initRpc, listener);
141         }
142
143         final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
144             @Override
145             public void onSuccess(final DeviceSources result) {
146                 addProvidedSourcesToSchemaRegistry(result);
147                 setUpSchema(result);
148             }
149
150             private void setUpSchema(final DeviceSources result) {
151                 processingExecutor.submit(new SchemaSetup(result, remoteSessionCapabilities, listener));
152             }
153
154             @Override
155             public void onFailure(final Throwable t) {
156                 LOG.warn("{}: Unexpected error resolving device sources: {}", id, t);
157                 handleSalInitializationFailure(t, listener);
158             }
159         };
160
161         Futures.addCallback(sourceResolverFuture, resolvedSourceCallback);
162     }
163
164     private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc, final NetconfDeviceCommunicator listener) {
165        // TODO check whether the model describing create subscription is present in schema
166         // 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)
167         final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultListenableFuture = deviceRpc.invokeRpc(
168             NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME),
169             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     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     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.stream().map(entry -> new AvailableCapabilityBuilder()
455                             .setCapability(entry.toString()).setCapabilityOrigin(remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
456                             .collect(Collectors.toList()));
457
458                     capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
459                             .setCapability(entry).setCapabilityOrigin(AvailableCapability.CapabilityOrigin.DeviceAdvertised).build())
460                             .collect(Collectors.toList()));
461
462                     handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
463                     return;
464                 } catch (final Throwable t) {
465                     if (t instanceof MissingSchemaSourceException){
466                         requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t);
467                     } else if (t instanceof SchemaResolutionException) {
468                         // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
469                         // that might be wrapping a MissingSchemaSourceException so we need to look
470                         // at the cause of the exception to make sure we don't misinterpret it.
471                         if (t.getCause() instanceof MissingSchemaSourceException) {
472                             requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t.getCause());
473                             continue;
474                         }
475                         requiredSources = handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t);
476                     } else {
477                         // unknown error, fail
478                         handleSalInitializationFailure(t, listener);
479                         return;
480                     }
481                 }
482             }
483             // No more sources, fail
484             final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context");
485             handleSalInitializationFailure(cause, listener);
486             salFacade.onDeviceFailed(cause);
487         }
488
489         private Collection<SourceIdentifier> handleMissingSchemaSourceException(final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException t) {
490             // In case source missing, try without it
491             final SourceIdentifier missingSource = t.getSourceId();
492             LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
493             LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", t);
494             final Collection<QName> qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
495             if (!qNameOfMissingSource.isEmpty()) {
496                 capabilities.addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
497             }
498             return stripUnavailableSource(requiredSources, missingSource);
499         }
500
501         private Collection<SourceIdentifier> handleSchemaResolutionException(final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
502             // In case resolution error, try only with resolved sources
503             // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
504             // FIXME Do we really have assurance that these two cases cannot happen at once?
505             if (resolutionException.getFailedSource() != null) {
506                 // flawed model - exclude it
507                 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
508                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, failedSourceId);
509                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, resolutionException);
510                 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
511                         UnavailableCapability.FailureReason.UnableToResolve);
512                 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
513             }
514             // unsatisfied imports
515             final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
516             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
517             LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
518             LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", resolutionException);
519             return resolutionException.getResolvedSources();
520         }
521
522         protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
523             return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
524         }
525
526         private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources, final SourceIdentifier sIdToRemove) {
527             final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
528             final boolean removed = sourceIdentifiers.remove(sIdToRemove);
529             Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources);
530             return sourceIdentifiers;
531         }
532
533         private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
534             final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
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())) {
546                     continue;
547                 }
548
549                 final String rev = getNullableRev(identifier);
550                 if (rev == null) {
551                     if (qname.getRevision() == null) {
552                         return qname;
553                     }
554                 } else if (qname.getFormattedRevision().equals(rev)) {
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         private String getNullableRev(final SourceIdentifier identifier) {
564             final String rev = identifier.getRevision();
565             return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? null : rev;
566         }
567     }
568 }