2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.client.mdsal;
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
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.MoreExecutors;
23 import com.google.common.util.concurrent.SettableFuture;
24 import java.io.Serial;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
31 import java.util.Objects;
33 import java.util.concurrent.CancellationException;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.Executor;
36 import java.util.stream.Collectors;
37 import org.checkerframework.checker.lock.qual.GuardedBy;
38 import org.eclipse.jdt.annotation.NonNull;
39 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
40 import org.opendaylight.netconf.api.CapabilityURN;
41 import org.opendaylight.netconf.api.messages.NetconfMessage;
42 import org.opendaylight.netconf.client.mdsal.api.BaseNetconfSchemas;
43 import org.opendaylight.netconf.client.mdsal.api.DeviceActionFactory;
44 import org.opendaylight.netconf.client.mdsal.api.NetconfDeviceSchemasResolver;
45 import org.opendaylight.netconf.client.mdsal.api.NetconfSessionPreferences;
46 import org.opendaylight.netconf.client.mdsal.api.RemoteDevice;
47 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceCommunicator;
48 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceHandler;
49 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
50 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices;
51 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices.Rpcs;
52 import org.opendaylight.netconf.client.mdsal.impl.BaseSchema;
53 import org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil;
54 import org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformer;
55 import org.opendaylight.netconf.client.mdsal.spi.NetconfDeviceRpc;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.Get;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscription;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
59 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240120.connection.oper.available.capabilities.AvailableCapability;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240120.connection.oper.available.capabilities.AvailableCapabilityBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240120.connection.oper.unavailable.capabilities.UnavailableCapability;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240120.connection.oper.unavailable.capabilities.UnavailableCapability.FailureReason;
64 import org.opendaylight.yangtools.concepts.Registration;
65 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
66 import org.opendaylight.yangtools.yang.common.QName;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.schema.MountPointContext;
70 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
71 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
72 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
73 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
74 import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
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.spi.SchemaSourceRegistry;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
84 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
86 public class NetconfDevice implements RemoteDevice<NetconfDeviceCommunicator> {
87 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
89 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
90 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
91 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.of(
92 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
94 protected final RemoteDeviceId id;
95 protected final EffectiveModelContextFactory schemaContextFactory;
96 protected final SchemaSourceRegistry schemaRegistry;
97 protected final SchemaRepository schemaRepository;
99 protected final List<Registration> sourceRegistrations = new ArrayList<>();
101 private final RemoteDeviceHandler salFacade;
102 private final Executor processingExecutor;
103 private final DeviceActionFactory deviceActionFactory;
104 private final NetconfDeviceSchemasResolver stateSchemasResolver;
105 private final NotificationHandler notificationHandler;
106 private final boolean reconnectOnSchemasChange;
107 private final BaseNetconfSchemas baseSchemas;
110 private ListenableFuture<List<Object>> schemaFuturesList;
112 private boolean connected = false;
114 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
115 final RemoteDeviceId id, final RemoteDeviceHandler salFacade, final Executor globalProcessingExecutor,
116 final boolean reconnectOnSchemasChange) {
117 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
120 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
121 final RemoteDeviceId id, final RemoteDeviceHandler salFacade, final Executor globalProcessingExecutor,
122 final boolean reconnectOnSchemasChange, final DeviceActionFactory deviceActionFactory) {
123 this.baseSchemas = requireNonNull(baseSchemas);
125 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
126 this.deviceActionFactory = deviceActionFactory;
127 schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
128 schemaRepository = schemaResourcesDTO.getSchemaRepository();
129 schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
130 this.salFacade = salFacade;
131 stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
132 processingExecutor = requireNonNull(globalProcessingExecutor);
133 notificationHandler = new NotificationHandler(salFacade, id);
137 public synchronized void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
138 final NetconfDeviceCommunicator listener) {
139 // SchemaContext setup has to be performed in a dedicated thread since we are in a Netty thread in this method
140 // YANG models are being downloaded in this method and it would cause a deadlock if we used the netty thread
141 // https://netty.io/wiki/thread-model.html
143 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
145 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
146 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.modelContext(), listener,
147 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
148 final var sourceResolverFuture = Futures.submit(new DeviceSourcesResolver(id, baseSchema, initRpc,
149 remoteSessionCapabilities, stateSchemasResolver), processingExecutor);
151 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
152 registerToBaseNetconfStream(initRpc, listener);
155 // Set up the EffectiveModelContext for the device
156 final var futureSchema = Futures.transformAsync(sourceResolverFuture,
157 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
159 // Potentially acquire mount point list and interpret it
160 final var netconfDeviceSchemaFuture = Futures.transformAsync(futureSchema,
161 result -> Futures.transform(createMountPointContext(result.modelContext(), baseSchema, listener),
162 mount -> new NetconfDeviceSchema(result.capabilities(), mount), processingExecutor),
164 schemaFuturesList = Futures.allAsList(sourceResolverFuture, futureSchema, netconfDeviceSchemaFuture);
166 Futures.addCallback(netconfDeviceSchemaFuture, new FutureCallback<>() {
168 public void onSuccess(final NetconfDeviceSchema result) {
169 handleSalInitializationSuccess(listener, result, remoteSessionCapabilities,
170 getDeviceSpecificRpc(result.mountContext(), listener, baseSchema));
174 public void onFailure(final Throwable cause) {
175 // The method onRemoteSessionDown was called while the EffectiveModelContext for the device
176 // was being processed.
177 if (cause instanceof CancellationException) {
178 LOG.warn("{}: Device communicator was tear down since the schema setup started", id);
180 handleSalInitializationFailure(listener, cause);
183 }, MoreExecutors.directExecutor());
186 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
187 final NetconfDeviceCommunicator listener) {
188 // TODO check whether the model describing create subscription is present in schema
189 // Perhaps add a default schema context to support create-subscription if the model was not provided
190 // (same as what we do for base netconf operations in transformer)
191 final var rpcResultListenableFuture = deviceRpc.domRpcService()
192 .invokeRpc(CreateSubscription.QNAME, Builders.containerBuilder()
193 .withNodeIdentifier(NodeIdentifier.create(CreateSubscriptionInput.QNAME))
194 // Note: default 'stream' is 'NETCONF', we do not need to create an explicit leaf
197 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
199 public void onSuccess(final DOMRpcResult domRpcResult) {
200 notificationHandler.addNotificationFilter(notification -> {
201 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().name().getNodeType())) {
202 LOG.info("{}: Schemas change detected, reconnecting", id);
203 // Only disconnect is enough,
204 // the reconnecting nature of the connector will take care of reconnecting
205 listener.disconnect();
213 public void onFailure(final Throwable throwable) {
214 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
217 }, MoreExecutors.directExecutor());
220 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
221 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
224 private synchronized void handleSalInitializationSuccess(final RemoteDeviceCommunicator listener,
225 final NetconfDeviceSchema deviceSchema, final NetconfSessionPreferences remoteSessionCapabilities,
226 final Rpcs deviceRpc) {
227 // NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
228 // since salFacade.onDeviceDisconnected was already called.
230 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
234 final var messageTransformer = new NetconfMessageTransformer(deviceSchema.mountContext(), true,
235 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
237 // Order is important here: salFacade has to see the device come up and then the notificationHandler can deliver
238 // whatever notifications have been held back
239 salFacade.onDeviceConnected(deviceSchema, remoteSessionCapabilities,
240 new RemoteDeviceServices(deviceRpc, deviceActionFactory == null ? null
241 : deviceActionFactory.createDeviceAction(messageTransformer, listener)));
242 notificationHandler.onRemoteSchemaUp(messageTransformer);
244 LOG.info("{}: Netconf connector initialized successfully", id);
247 private void handleSalInitializationFailure(final RemoteDeviceCommunicator listener, final Throwable cause) {
248 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
250 cleanupInitialization();
251 salFacade.onDeviceFailed(cause);
254 private synchronized void cleanupInitialization() {
256 if (schemaFuturesList != null && !schemaFuturesList.isDone()) {
257 if (!schemaFuturesList.cancel(true)) {
258 LOG.warn("The cleanup of Schema Futures for device {} was unsuccessful.", id);
261 notificationHandler.onRemoteSchemaDown();
262 sourceRegistrations.forEach(Registration::close);
263 sourceRegistrations.clear();
266 private synchronized void setConnected(final boolean connected) {
267 this.connected = connected;
270 private ListenableFuture<SchemaResult> assembleSchemaContext(final DeviceSources deviceSources,
271 final NetconfSessionPreferences remoteSessionCapabilities) {
272 LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
274 sourceRegistrations.addAll(deviceSources.register(schemaRegistry));
276 return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
279 private ListenableFuture<@NonNull MountPointContext> createMountPointContext(
280 final EffectiveModelContext schemaContext, final BaseSchema baseSchema,
281 final NetconfDeviceCommunicator listener) {
282 final MountPointContext emptyContext = MountPointContext.of(schemaContext);
283 if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
284 return Futures.immediateFuture(emptyContext);
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));
292 return Futures.transform(deviceRpc.domRpcService().invokeRpc(Get.QNAME, ImmutableNodes.newContainerBuilder()
293 .withNodeIdentifier(NETCONF_GET_NODEID)
294 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
295 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
298 private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
299 final var errors = rpcResult.errors();
300 if (!errors.isEmpty()) {
301 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
303 final var schemaMounts = rpcResult.value();
304 if (schemaMounts == null) {
305 LOG.debug("{}: device does not define any schema mounts", id);
309 return DeviceMountPointContext.create(emptyContext, schemaMounts);
313 public void onRemoteSessionDown() {
314 cleanupInitialization();
315 salFacade.onDeviceDisconnected();
319 public void onNotification(final NetconfMessage notification) {
320 notificationHandler.handleNotification(notification);
323 private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
324 return notificationSupport ? baseSchemas.baseSchemaWithNotifications() : baseSchemas.baseSchema();
327 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
328 final RemoteDeviceCommunicator listener, final BaseSchema schema) {
329 return new NetconfDeviceRpc(result.modelContext(), listener,
330 new NetconfMessageTransformer(result, true, schema));
334 * Just a transfer object containing schema related dependencies. Injected in constructor.
336 public static class SchemaResourcesDTO {
337 private final SchemaSourceRegistry schemaRegistry;
338 private final SchemaRepository schemaRepository;
339 private final EffectiveModelContextFactory schemaContextFactory;
340 private final NetconfDeviceSchemasResolver stateSchemasResolver;
342 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
343 final SchemaRepository schemaRepository,
344 final EffectiveModelContextFactory schemaContextFactory,
345 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
346 this.schemaRegistry = requireNonNull(schemaRegistry);
347 this.schemaRepository = requireNonNull(schemaRepository);
348 this.schemaContextFactory = requireNonNull(schemaContextFactory);
349 stateSchemasResolver = requireNonNull(deviceSchemasResolver);
352 public SchemaSourceRegistry getSchemaRegistry() {
353 return schemaRegistry;
356 public SchemaRepository getSchemaRepository() {
357 return schemaRepository;
360 public EffectiveModelContextFactory getSchemaContextFactory() {
361 return schemaContextFactory;
364 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
365 return stateSchemasResolver;
370 * A dedicated exception to indicate when we fail to setup an {@link EffectiveModelContext}.
372 public static final class EmptySchemaContextException extends Exception {
374 private static final long serialVersionUID = 1L;
376 public EmptySchemaContextException(final String message) {
382 * {@link NetconfDeviceCapabilities} and {@link EffectiveModelContext}.
384 private record SchemaResult(
385 @NonNull NetconfDeviceCapabilities capabilities,
386 @NonNull EffectiveModelContext modelContext) {
389 requireNonNull(capabilities);
390 requireNonNull(modelContext);
395 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
397 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
398 private final SettableFuture<SchemaResult> resultFuture = SettableFuture.create();
400 private final Set<AvailableCapability> nonModuleBasedCapabilities = new HashSet<>();
401 private final Map<QName, FailureReason> unresolvedCapabilites = new HashMap<>();
402 private final Set<AvailableCapability> resolvedCapabilities = new HashSet<>();
404 private final DeviceSources deviceSources;
405 private final NetconfSessionPreferences remoteSessionCapabilities;
407 private Collection<SourceIdentifier> requiredSources;
409 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
410 this.deviceSources = deviceSources;
411 this.remoteSessionCapabilities = remoteSessionCapabilities;
413 // If device supports notifications and does not contain necessary modules, add them automatically
414 if (remoteSessionCapabilities.containsNonModuleCapability(CapabilityURN.NOTIFICATION)) {
415 // FIXME: mutable collection modification!
416 deviceSources.getRequiredSourcesQName().addAll(List.of(
417 org.opendaylight.yang.svc.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
418 .YangModuleInfoImpl.getInstance().getName(),
419 org.opendaylight.yang.svc.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
420 .YangModuleInfoImpl.getInstance().getName())
424 requiredSources = deviceSources.getRequiredSources();
425 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
427 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
428 UnavailableCapability.FailureReason.MissingSource);
429 requiredSources.removeAll(missingSources);
432 ListenableFuture<SchemaResult> startResolution() {
438 public void onSuccess(final EffectiveModelContext result) {
439 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
441 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
442 unresolvedCapabilites.keySet());
443 resolvedCapabilities.addAll(filteredQNames.stream()
444 .map(capability -> new AvailableCapabilityBuilder()
445 .setCapability(capability.toString())
446 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
448 .collect(Collectors.toList()));
450 nonModuleBasedCapabilities.addAll(remoteSessionCapabilities.nonModuleCaps().keySet().stream()
451 .map(capability -> new AvailableCapabilityBuilder()
452 .setCapability(capability)
453 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
455 .collect(Collectors.toList()));
458 resultFuture.set(new SchemaResult(new NetconfDeviceCapabilities(ImmutableMap.copyOf(unresolvedCapabilites),
459 ImmutableSet.copyOf(resolvedCapabilities), ImmutableSet.copyOf(nonModuleBasedCapabilities)), result));
463 public void onFailure(final Throwable cause) {
464 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
465 // that might be wrapping a MissingSchemaSourceException so we need to look
466 // at the cause of the exception to make sure we don't misinterpret it.
467 if (cause instanceof MissingSchemaSourceException) {
468 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
469 } else if (cause instanceof SchemaResolutionException) {
470 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
472 LOG.debug("Unhandled failure", cause);
473 resultFuture.setException(cause);
481 private void trySetupSchema() {
482 if (!requiredSources.isEmpty()) {
483 // Initiate async resolution, drive it back based on the result
484 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
485 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
486 MoreExecutors.directExecutor());
488 LOG.debug("{}: no more sources for schema context", id);
489 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
493 private List<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
494 return origSources.parallelStream().filter(sourceIdentifier -> {
496 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSource.class).get();
498 } catch (InterruptedException | ExecutionException e) {
501 }).collect(Collectors.toList());
504 private void addUnresolvedCapabilities(final Collection<QName> capabilities, final FailureReason reason) {
505 for (QName s : capabilities) {
506 unresolvedCapabilites.put(s, reason);
510 private List<SourceIdentifier> handleMissingSchemaSourceException(
511 final MissingSchemaSourceException exception) {
512 // In case source missing, try without it
513 final SourceIdentifier missingSource = exception.sourceId();
514 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
516 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
517 id, missingSource, exception);
518 final var qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
519 if (!qNameOfMissingSource.isEmpty()) {
520 addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
522 return stripUnavailableSource(missingSource);
525 private Collection<SourceIdentifier> handleSchemaResolutionException(
526 final SchemaResolutionException resolutionException) {
527 // In case resolution error, try only with resolved sources
528 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
529 // FIXME Do we really have assurance that these two cases cannot happen at once?
530 final var failedSourceId = resolutionException.sourceId();
531 if (failedSourceId != null) {
532 // flawed model - exclude it
533 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
535 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
536 id, failedSourceId, resolutionException);
537 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(List.of(failedSourceId)),
538 UnavailableCapability.FailureReason.UnableToResolve);
539 return stripUnavailableSource(failedSourceId);
541 // unsatisfied imports
542 addUnresolvedCapabilities(
543 getQNameFromSourceIdentifiers(resolutionException.getUnsatisfiedImports().keySet()),
544 UnavailableCapability.FailureReason.UnableToResolve);
545 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
546 id, resolutionException.getUnsatisfiedImports());
547 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
548 id, resolutionException.getUnsatisfiedImports(), resolutionException);
549 return resolutionException.getResolvedSources();
552 private List<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
553 final var tmp = new ArrayList<>(requiredSources);
554 checkState(tmp.remove(sourceIdToRemove), "%s: Trying to remove %s from %s failed", id, sourceIdToRemove,
559 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
560 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
562 if (qNames.isEmpty()) {
563 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
566 return Collections2.filter(qNames, Predicates.notNull());
569 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
570 // Required sources are all required and provided merged in DeviceSourcesResolver
571 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
572 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
576 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
580 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
581 deviceSources.getRequiredSourcesQName());
582 // return null since we cannot find the QName,
583 // this capability will be removed from required sources and not reported as unresolved-capability