Merge "Bug 8153: Enforce check-style rules for netconf - mdsal-netconf-notification"
[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,
205                                         final NetconfSessionPreferences remoteSessionCapabilities,
206                                         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     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.stream().map(entry -> new AvailableCapabilityBuilder()
456                             .setCapability(entry.toString()).setCapabilityOrigin(remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
457                             .collect(Collectors.toList()));
458
459                     capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
460                             .setCapability(entry).setCapabilityOrigin(remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
461                             .collect(Collectors.toList()));
462
463                     handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
464                     return;
465                 } catch (final Throwable t) {
466                     if (t instanceof MissingSchemaSourceException){
467                         requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t);
468                     } else if (t instanceof SchemaResolutionException) {
469                         // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
470                         // that might be wrapping a MissingSchemaSourceException so we need to look
471                         // at the cause of the exception to make sure we don't misinterpret it.
472                         if (t.getCause() instanceof MissingSchemaSourceException) {
473                             requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t.getCause());
474                             continue;
475                         }
476                         requiredSources = handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t);
477                     } else {
478                         // unknown error, fail
479                         handleSalInitializationFailure(t, listener);
480                         return;
481                     }
482                 }
483             }
484             // No more sources, fail
485             final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context");
486             handleSalInitializationFailure(cause, listener);
487             salFacade.onDeviceFailed(cause);
488         }
489
490         private Collection<SourceIdentifier> handleMissingSchemaSourceException(final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException t) {
491             // In case source missing, try without it
492             final SourceIdentifier missingSource = t.getSourceId();
493             LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
494             LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", t);
495             final Collection<QName> qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
496             if (!qNameOfMissingSource.isEmpty()) {
497                 capabilities.addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
498             }
499             return stripUnavailableSource(requiredSources, missingSource);
500         }
501
502         private Collection<SourceIdentifier> handleSchemaResolutionException(final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
503             // In case resolution error, try only with resolved sources
504             // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
505             // FIXME Do we really have assurance that these two cases cannot happen at once?
506             if (resolutionException.getFailedSource() != null) {
507                 // flawed model - exclude it
508                 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
509                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, failedSourceId);
510                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, resolutionException);
511                 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
512                         UnavailableCapability.FailureReason.UnableToResolve);
513                 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
514             }
515             // unsatisfied imports
516             final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
517             capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
518             LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
519             LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", resolutionException);
520             return resolutionException.getResolvedSources();
521         }
522
523         protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
524             return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
525         }
526
527         private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources, final SourceIdentifier sIdToRemove) {
528             final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
529             final boolean removed = sourceIdentifiers.remove(sIdToRemove);
530             Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources);
531             return sourceIdentifiers;
532         }
533
534         private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
535             final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
536
537             if (qNames.isEmpty()) {
538                 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, identifiers);
539             }
540             return Collections2.filter(qNames, Predicates.notNull());
541         }
542
543         private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
544             // Required sources are all required and provided merged in DeviceSourcesResolver
545             for (final QName qname : deviceSources.getRequiredSourcesQName()) {
546                 if (!qname.getLocalName().equals(identifier.getName())) {
547                     continue;
548                 }
549
550                 final String rev = getNullableRev(identifier);
551                 if (rev == null) {
552                     if (qname.getRevision() == null) {
553                         return qname;
554                     }
555                 } else if (qname.getFormattedRevision().equals(rev)) {
556                     return qname;
557                 }
558             }
559             LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier, deviceSources.getRequiredSourcesQName());
560             // return null since we cannot find the QName, this capability will be removed from required sources and not reported as unresolved-capability
561             return null;
562         }
563
564         private String getNullableRev(final SourceIdentifier identifier) {
565             final String rev = identifier.getRevision();
566             return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? null : rev;
567         }
568     }
569 }