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