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