Add RemoteDeviceServices
[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 com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
13
14 import com.google.common.base.Predicates;
15 import com.google.common.collect.Collections2;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.Sets;
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 com.google.common.util.concurrent.SettableFuture;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Objects;
33 import java.util.Set;
34 import java.util.concurrent.ExecutionException;
35 import java.util.stream.Collectors;
36 import org.checkerframework.checker.lock.qual.GuardedBy;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
39 import org.opendaylight.mdsal.dom.api.DOMRpcService;
40 import org.opendaylight.netconf.api.NetconfMessage;
41 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
42 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
43 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
44 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
45 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
46 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
47 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
48 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceServices;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
50 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
51 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
52 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
53 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseNetconfSchemas;
54 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
55 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
56 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
57 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability.FailureReason;
63 import org.opendaylight.yangtools.concepts.Registration;
64 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
65 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
66 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
67 import org.opendaylight.yangtools.yang.common.QName;
68 import org.opendaylight.yangtools.yang.common.RpcError;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
71 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
73 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
74 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
75 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
76 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
77 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
78 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
79 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
80 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
81 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84
85 /**
86  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
87  */
88 public class NetconfDevice implements RemoteDevice<NetconfDeviceCommunicator> {
89     private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
90
91     private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
92         SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
93     private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
94         NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
95
96     protected final RemoteDeviceId id;
97     protected final EffectiveModelContextFactory schemaContextFactory;
98     protected final SchemaSourceRegistry schemaRegistry;
99     protected final SchemaRepository schemaRepository;
100
101     protected final List<Registration> sourceRegistrations = new ArrayList<>();
102
103     private final RemoteDeviceHandler salFacade;
104     private final ListeningExecutorService processingExecutor;
105     private final DeviceActionFactory deviceActionFactory;
106     private final NetconfDeviceSchemasResolver stateSchemasResolver;
107     private final NotificationHandler notificationHandler;
108     private final boolean reconnectOnSchemasChange;
109     private final BaseNetconfSchemas baseSchemas;
110
111     @GuardedBy("this")
112     private boolean connected = false;
113
114     // Message transformer is constructed once the schemas are available
115     private MessageTransformer messageTransformer;
116
117     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
118             final RemoteDeviceId id, final RemoteDeviceHandler salFacade,
119             final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
120         this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
121     }
122
123     public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
124             final RemoteDeviceId id, final RemoteDeviceHandler salFacade,
125             final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
126             final DeviceActionFactory deviceActionFactory) {
127         this.baseSchemas = requireNonNull(baseSchemas);
128         this.id = id;
129         this.reconnectOnSchemasChange = reconnectOnSchemasChange;
130         this.deviceActionFactory = deviceActionFactory;
131         schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
132         schemaRepository = schemaResourcesDTO.getSchemaRepository();
133         schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
134         this.salFacade = salFacade;
135         stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
136         processingExecutor = requireNonNull(globalProcessingExecutor);
137         notificationHandler = new NotificationHandler(salFacade, id);
138     }
139
140     @Override
141     public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
142                                   final NetconfDeviceCommunicator listener) {
143         // SchemaContext setup has to be performed in a dedicated thread since
144         // we are in a netty thread in this method
145         // Yang models are being downloaded in this method and it would cause a
146         // deadlock if we used the netty thread
147         // http://netty.io/wiki/thread-model.html
148         setConnected(true);
149         LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
150
151         final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
152         final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
153             new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
154         final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
155             new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
156
157         if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
158             registerToBaseNetconfStream(initRpc, listener);
159         }
160
161         // Set up the SchemaContext for the device
162         final ListenableFuture<SchemaResult> futureSchema = Futures.transformAsync(sourceResolverFuture,
163             deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
164
165         // Potentially acquire mount point list and interpret it
166         final ListenableFuture<NetconfDeviceSchema> futureContext = Futures.transformAsync(futureSchema,
167             result -> Futures.transform(createMountPointContext(result.modelContext(), baseSchema, listener),
168                 mount -> new NetconfDeviceSchema(result.capabilities(), mount), processingExecutor),
169             processingExecutor);
170
171         Futures.addCallback(futureContext, new FutureCallback<>() {
172             @Override
173             public void onSuccess(final NetconfDeviceSchema result) {
174                 handleSalInitializationSuccess(result, remoteSessionCapabilities,
175                         getDeviceSpecificRpc(result.mountContext(), listener, baseSchema), listener);
176             }
177
178             @Override
179             public void onFailure(final Throwable cause) {
180                 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
181                 // FIXME: this causes salFacade to see onDeviceDisconnected() and then onDeviceFailed(), which is quite
182                 //        weird
183                 handleSalInitializationFailure(cause, listener);
184                 salFacade.onDeviceFailed(cause);
185             }
186         }, MoreExecutors.directExecutor());
187     }
188
189     private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
190                                              final NetconfDeviceCommunicator listener) {
191         // TODO check whether the model describing create subscription is present in schema
192         // Perhaps add a default schema context to support create-subscription if the model was not provided
193         // (same as what we do for base netconf operations in transformer)
194         final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
195                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
196                 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
197
198         Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
199             @Override
200             public void onSuccess(final DOMRpcResult domRpcResult) {
201                 notificationHandler.addNotificationFilter(notification -> {
202                     if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getIdentifier().getNodeType())) {
203                         LOG.info("{}: Schemas change detected, reconnecting", id);
204                         // Only disconnect is enough,
205                         // the reconnecting nature of the connector will take care of reconnecting
206                         listener.disconnect();
207                         return false;
208                     }
209                     return true;
210                 });
211             }
212
213             @Override
214             public void onFailure(final Throwable throwable) {
215                 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
216                         throwable);
217             }
218         }, MoreExecutors.directExecutor());
219     }
220
221     private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
222         return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
223     }
224
225     private synchronized void handleSalInitializationSuccess(final NetconfDeviceSchema deviceSchema,
226             final NetconfSessionPreferences remoteSessionCapabilities, final DOMRpcService deviceRpc,
227             final RemoteDeviceCommunicator listener) {
228         //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
229         //since salFacade.onDeviceDisconnected was already called.
230         if (connected) {
231             final var mount = deviceSchema.mountContext();
232             messageTransformer = new NetconfMessageTransformer(mount, true,
233                 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
234
235             // salFacade.onDeviceConnected has to be called before the notification handler is initialized
236             salFacade.onDeviceConnected(deviceSchema, remoteSessionCapabilities,
237                 new RemoteDeviceServices(deviceRpc, deviceActionFactory == null ? null
238                     : deviceActionFactory.createDeviceAction(messageTransformer, listener,
239                         mount.getEffectiveModelContext())));
240             notificationHandler.onRemoteSchemaUp(messageTransformer);
241
242             LOG.info("{}: Netconf connector initialized successfully", id);
243         } else {
244             LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
245         }
246     }
247
248     private void handleSalInitializationFailure(final Throwable throwable, final RemoteDeviceCommunicator listener) {
249         LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
250         listener.close();
251         onRemoteSessionDown();
252         resetMessageTransformer();
253     }
254
255     /**
256      * Set the transformer to null as is in initial state.
257      */
258     private void resetMessageTransformer() {
259         updateTransformer(null);
260     }
261
262     private synchronized void updateTransformer(final MessageTransformer transformer) {
263         messageTransformer = transformer;
264     }
265
266     private synchronized void setConnected(final boolean connected) {
267         this.connected = connected;
268     }
269
270     private ListenableFuture<SchemaResult> assembleSchemaContext(final DeviceSources deviceSources,
271             final NetconfSessionPreferences remoteSessionCapabilities) {
272         LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
273
274         sourceRegistrations.addAll(deviceSources.register(schemaRegistry));
275
276         return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
277     }
278
279     private ListenableFuture<@NonNull MountPointContext> createMountPointContext(
280             final EffectiveModelContext schemaContext, final BaseSchema baseSchema,
281             final NetconfDeviceCommunicator listener) {
282         final MountPointContext emptyContext = new EmptyMountPointContext(schemaContext);
283         if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
284             return Futures.immediateFuture(emptyContext);
285         }
286
287         // Create a temporary RPC invoker and acquire the mount point tree
288         LOG.debug("{}: Acquiring available mount points", id);
289         final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
290             new NetconfMessageTransformer(emptyContext, false, baseSchema));
291
292         return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
293             Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
294                 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
295                 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
296     }
297
298     private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
299         final Collection<? extends RpcError> errors = rpcResult.getErrors();
300         if (!errors.isEmpty()) {
301             LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
302         }
303         final NormalizedNode schemaMounts = rpcResult.getResult();
304         if (schemaMounts == null) {
305             LOG.debug("{}: device does not define any schema mounts", id);
306             return emptyContext;
307         }
308         if (!(schemaMounts instanceof ContainerNode)) {
309             LOG.warn("{}: ignoring non-container schema mounts {}", id, schemaMounts);
310             return emptyContext;
311         }
312
313         return DeviceMountPointContext.create(emptyContext, (ContainerNode) schemaMounts);
314     }
315
316     @Override
317     public void onRemoteSessionDown() {
318         setConnected(false);
319         notificationHandler.onRemoteSchemaDown();
320
321         salFacade.onDeviceDisconnected();
322         sourceRegistrations.forEach(Registration::close);
323         sourceRegistrations.clear();
324         resetMessageTransformer();
325     }
326
327     @Override
328     public void onRemoteSessionFailed(final Throwable throwable) {
329         setConnected(false);
330         salFacade.onDeviceFailed(throwable);
331     }
332
333     @Override
334     public void onNotification(final NetconfMessage notification) {
335         notificationHandler.handleNotification(notification);
336     }
337
338     private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
339         return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
340     }
341
342     protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
343             final RemoteDeviceCommunicator listener, final BaseSchema schema) {
344         return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
345             new NetconfMessageTransformer(result, true, schema));
346     }
347
348     /**
349      * Just a transfer object containing schema related dependencies. Injected in constructor.
350      */
351     public static class SchemaResourcesDTO {
352         private final SchemaSourceRegistry schemaRegistry;
353         private final SchemaRepository schemaRepository;
354         private final EffectiveModelContextFactory schemaContextFactory;
355         private final NetconfDeviceSchemasResolver stateSchemasResolver;
356
357         public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
358                                   final SchemaRepository schemaRepository,
359                                   final EffectiveModelContextFactory schemaContextFactory,
360                                   final NetconfDeviceSchemasResolver deviceSchemasResolver) {
361             this.schemaRegistry = requireNonNull(schemaRegistry);
362             this.schemaRepository = requireNonNull(schemaRepository);
363             this.schemaContextFactory = requireNonNull(schemaContextFactory);
364             stateSchemasResolver = requireNonNull(deviceSchemasResolver);
365         }
366
367         public SchemaSourceRegistry getSchemaRegistry() {
368             return schemaRegistry;
369         }
370
371         public SchemaRepository getSchemaRepository() {
372             return schemaRepository;
373         }
374
375         public EffectiveModelContextFactory getSchemaContextFactory() {
376             return schemaContextFactory;
377         }
378
379         public NetconfDeviceSchemasResolver getStateSchemasResolver() {
380             return stateSchemasResolver;
381         }
382     }
383
384     /**
385      * A dedicated exception to indicate when we fail to setup an {@link EffectiveModelContext}.
386      */
387     public static final class EmptySchemaContextException extends Exception {
388         private static final long serialVersionUID = 1L;
389
390         public EmptySchemaContextException(final String message) {
391             super(message);
392         }
393     }
394
395     /**
396      * {@link NetconfDeviceCapabilities} and {@link EffectiveModelContext}.
397      */
398     private record SchemaResult(
399         @NonNull NetconfDeviceCapabilities capabilities,
400         @NonNull EffectiveModelContext modelContext) {
401
402         SchemaResult {
403             requireNonNull(capabilities);
404             requireNonNull(modelContext);
405         }
406     }
407
408     /**
409      * Schema builder that tries to build schema context from provided sources or biggest subset of it.
410      */
411     private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
412         private final SettableFuture<SchemaResult> resultFuture = SettableFuture.create();
413
414         private final Set<AvailableCapability> nonModuleBasedCapabilities = new HashSet<>();
415         private final Map<QName, FailureReason> unresolvedCapabilites = new HashMap<>();
416         private final Set<AvailableCapability> resolvedCapabilities = new HashSet<>();
417
418         private final DeviceSources deviceSources;
419         private final NetconfSessionPreferences remoteSessionCapabilities;
420
421         private Collection<SourceIdentifier> requiredSources;
422
423         SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
424             this.deviceSources = deviceSources;
425             this.remoteSessionCapabilities = remoteSessionCapabilities;
426
427             // If device supports notifications and does not contain necessary modules, add them automatically
428             if (remoteSessionCapabilities.containsNonModuleCapability(
429                     XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0)) {
430                 deviceSources.getRequiredSourcesQName().addAll(
431                         Arrays.asList(
432                                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
433                                         .$YangModuleInfoImpl.getInstance().getName(),
434                                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
435                                         .$YangModuleInfoImpl.getInstance().getName()
436                         )
437                 );
438             }
439
440             requiredSources = deviceSources.getRequiredSources();
441             final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
442
443             addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
444                 UnavailableCapability.FailureReason.MissingSource);
445             requiredSources.removeAll(missingSources);
446         }
447
448         ListenableFuture<SchemaResult> startResolution() {
449             trySetupSchema();
450             return resultFuture;
451         }
452
453         @Override
454         public void onSuccess(final EffectiveModelContext result) {
455             LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
456
457             final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
458                     unresolvedCapabilites.keySet());
459             resolvedCapabilities.addAll(filteredQNames.stream()
460                 .map(capability -> new AvailableCapabilityBuilder()
461                     .setCapability(capability.toString())
462                     .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
463                     .build())
464                 .collect(Collectors.toList()));
465
466             nonModuleBasedCapabilities.addAll(remoteSessionCapabilities.nonModuleCaps().keySet().stream()
467                 .map(capability -> new AvailableCapabilityBuilder()
468                     .setCapability(capability)
469                     .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
470                     .build())
471                 .collect(Collectors.toList()));
472
473
474             resultFuture.set(new SchemaResult(new NetconfDeviceCapabilities(ImmutableMap.copyOf(unresolvedCapabilites),
475                 ImmutableSet.copyOf(resolvedCapabilities), ImmutableSet.copyOf(nonModuleBasedCapabilities)), result));
476         }
477
478         @Override
479         public void onFailure(final Throwable cause) {
480             // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
481             // that might be wrapping a MissingSchemaSourceException so we need to look
482             // at the cause of the exception to make sure we don't misinterpret it.
483             if (cause instanceof MissingSchemaSourceException) {
484                 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
485             } else if (cause instanceof SchemaResolutionException) {
486                 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
487             } else {
488                 LOG.debug("Unhandled failure", cause);
489                 resultFuture.setException(cause);
490                 // No more trying...
491                 return;
492             }
493
494             trySetupSchema();
495         }
496
497         private void trySetupSchema() {
498             if (!requiredSources.isEmpty()) {
499                 // Initiate async resolution, drive it back based on the result
500                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
501                 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
502                     MoreExecutors.directExecutor());
503             } else {
504                 LOG.debug("{}: no more sources for schema context", id);
505                 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
506             }
507         }
508
509         private List<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
510             return origSources.parallelStream().filter(sourceIdentifier -> {
511                 try {
512                     schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
513                     return false;
514                 } catch (InterruptedException | ExecutionException e) {
515                     return true;
516                 }
517             }).collect(Collectors.toList());
518         }
519
520         private void addUnresolvedCapabilities(final Collection<QName> capabilities, final FailureReason reason) {
521             for (QName s : capabilities) {
522                 unresolvedCapabilites.put(s, reason);
523             }
524         }
525
526         private List<SourceIdentifier> handleMissingSchemaSourceException(
527                 final MissingSchemaSourceException exception) {
528             // In case source missing, try without it
529             final SourceIdentifier missingSource = exception.getSourceId();
530             LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
531                 id, missingSource);
532             LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
533                 id, missingSource, exception);
534             final var qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
535             if (!qNameOfMissingSource.isEmpty()) {
536                 addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
537             }
538             return stripUnavailableSource(missingSource);
539         }
540
541         private Collection<SourceIdentifier> handleSchemaResolutionException(
542                 final SchemaResolutionException resolutionException) {
543             // In case resolution error, try only with resolved sources
544             // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
545             // FIXME Do we really have assurance that these two cases cannot happen at once?
546             if (resolutionException.getFailedSource() != null) {
547                 // flawed model - exclude it
548                 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
549                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
550                     id, failedSourceId);
551                 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
552                     id, failedSourceId, resolutionException);
553                 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(List.of(failedSourceId)),
554                         UnavailableCapability.FailureReason.UnableToResolve);
555                 return stripUnavailableSource(resolutionException.getFailedSource());
556             }
557             // unsatisfied imports
558             addUnresolvedCapabilities(
559                 getQNameFromSourceIdentifiers(resolutionException.getUnsatisfiedImports().keySet()),
560                 UnavailableCapability.FailureReason.UnableToResolve);
561             LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
562                 id, resolutionException.getUnsatisfiedImports());
563             LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
564                 id, resolutionException.getUnsatisfiedImports(), resolutionException);
565             return resolutionException.getResolvedSources();
566         }
567
568         private List<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
569             final var tmp = new ArrayList<>(requiredSources);
570             checkState(tmp.remove(sourceIdToRemove), "%s: Trying to remove %s from %s failed", id, sourceIdToRemove,
571                 requiredSources);
572             return tmp;
573         }
574
575         private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
576             final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
577
578             if (qNames.isEmpty()) {
579                 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
580                         identifiers);
581             }
582             return Collections2.filter(qNames, Predicates.notNull());
583         }
584
585         private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
586             // Required sources are all required and provided merged in DeviceSourcesResolver
587             for (final QName qname : deviceSources.getRequiredSourcesQName()) {
588                 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
589                     continue;
590                 }
591
592                 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
593                     return qname;
594                 }
595             }
596             LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
597                     deviceSources.getRequiredSourcesQName());
598             // return null since we cannot find the QName,
599             // this capability will be removed from required sources and not reported as unresolved-capability
600             return null;
601         }
602     }
603 }