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.model.api.EffectiveModelContext;
72 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
73 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
74 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
75 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
76 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
77 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
78 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
83 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
85 public class NetconfDevice implements RemoteDevice<NetconfDeviceCommunicator> {
86 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
88 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
89 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
90 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.of(
91 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
93 protected final RemoteDeviceId id;
94 protected final EffectiveModelContextFactory schemaContextFactory;
95 protected final SchemaSourceRegistry schemaRegistry;
96 protected final SchemaRepository schemaRepository;
98 protected final List<Registration> sourceRegistrations = new ArrayList<>();
100 private final RemoteDeviceHandler salFacade;
101 private final Executor processingExecutor;
102 private final DeviceActionFactory deviceActionFactory;
103 private final NetconfDeviceSchemasResolver stateSchemasResolver;
104 private final NotificationHandler notificationHandler;
105 private final boolean reconnectOnSchemasChange;
106 private final BaseNetconfSchemas baseSchemas;
109 private ListenableFuture<List<Object>> schemaFuturesList;
111 private boolean connected = false;
113 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
114 final RemoteDeviceId id, final RemoteDeviceHandler salFacade, final Executor globalProcessingExecutor,
115 final boolean reconnectOnSchemasChange) {
116 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
119 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
120 final RemoteDeviceId id, final RemoteDeviceHandler salFacade, final Executor globalProcessingExecutor,
121 final boolean reconnectOnSchemasChange, final DeviceActionFactory deviceActionFactory) {
122 this.baseSchemas = requireNonNull(baseSchemas);
124 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
125 this.deviceActionFactory = deviceActionFactory;
126 schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
127 schemaRepository = schemaResourcesDTO.getSchemaRepository();
128 schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
129 this.salFacade = salFacade;
130 stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
131 processingExecutor = requireNonNull(globalProcessingExecutor);
132 notificationHandler = new NotificationHandler(salFacade, id);
136 public synchronized void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
137 final NetconfDeviceCommunicator listener) {
138 // SchemaContext setup has to be performed in a dedicated thread since we are in a Netty thread in this method
139 // YANG models are being downloaded in this method and it would cause a deadlock if we used the netty thread
140 // https://netty.io/wiki/thread-model.html
142 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
144 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
145 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
146 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
147 final var sourceResolverFuture = Futures.submit(new DeviceSourcesResolver(id, baseSchema, initRpc,
148 remoteSessionCapabilities, stateSchemasResolver), processingExecutor);
150 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
151 registerToBaseNetconfStream(initRpc, listener);
154 // Set up the EffectiveModelContext for the device
155 final var futureSchema = Futures.transformAsync(sourceResolverFuture,
156 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
158 // Potentially acquire mount point list and interpret it
159 final var netconfDeviceSchemaFuture = Futures.transformAsync(futureSchema,
160 result -> Futures.transform(createMountPointContext(result.modelContext(), baseSchema, listener),
161 mount -> new NetconfDeviceSchema(result.capabilities(), mount), processingExecutor),
163 schemaFuturesList = Futures.allAsList(sourceResolverFuture, futureSchema, netconfDeviceSchemaFuture);
165 Futures.addCallback(netconfDeviceSchemaFuture, new FutureCallback<>() {
167 public void onSuccess(final NetconfDeviceSchema result) {
168 handleSalInitializationSuccess(listener, result, remoteSessionCapabilities,
169 getDeviceSpecificRpc(result.mountContext(), listener, baseSchema));
173 public void onFailure(final Throwable cause) {
174 // The method onRemoteSessionDown was called while the EffectiveModelContext for the device
175 // was being processed.
176 if (cause instanceof CancellationException) {
177 LOG.warn("{}: Device communicator was tear down since the schema setup started", id);
179 handleSalInitializationFailure(listener, cause);
182 }, MoreExecutors.directExecutor());
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 var rpcResultListenableFuture = deviceRpc.domRpcService()
191 .invokeRpc(CreateSubscription.QNAME, Builders.containerBuilder()
192 .withNodeIdentifier(NodeIdentifier.create(CreateSubscriptionInput.QNAME))
193 // Note: default 'stream' is 'NETCONF', we do not need to create an explicit leaf
196 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
198 public void onSuccess(final DOMRpcResult domRpcResult) {
199 notificationHandler.addNotificationFilter(notification -> {
200 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().name().getNodeType())) {
201 LOG.info("{}: Schemas change detected, reconnecting", id);
202 // Only disconnect is enough,
203 // the reconnecting nature of the connector will take care of reconnecting
204 listener.disconnect();
212 public void onFailure(final Throwable throwable) {
213 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
216 }, MoreExecutors.directExecutor());
219 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
220 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
223 private synchronized void handleSalInitializationSuccess(final RemoteDeviceCommunicator listener,
224 final NetconfDeviceSchema deviceSchema, final NetconfSessionPreferences remoteSessionCapabilities,
225 final Rpcs deviceRpc) {
226 // NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
227 // since salFacade.onDeviceDisconnected was already called.
229 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
233 final var messageTransformer = new NetconfMessageTransformer(deviceSchema.mountContext(), true,
234 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
236 // Order is important here: salFacade has to see the device come up and then the notificationHandler can deliver
237 // whatever notifications have been held back
238 salFacade.onDeviceConnected(deviceSchema, remoteSessionCapabilities,
239 new RemoteDeviceServices(deviceRpc, deviceActionFactory == null ? null
240 : deviceActionFactory.createDeviceAction(messageTransformer, listener)));
241 notificationHandler.onRemoteSchemaUp(messageTransformer);
243 LOG.info("{}: Netconf connector initialized successfully", id);
246 private void handleSalInitializationFailure(final RemoteDeviceCommunicator listener, final Throwable cause) {
247 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
249 cleanupInitialization();
250 salFacade.onDeviceFailed(cause);
253 private synchronized void cleanupInitialization() {
255 if (schemaFuturesList != null && !schemaFuturesList.isDone()) {
256 if (!schemaFuturesList.cancel(true)) {
257 LOG.warn("The cleanup of Schema Futures for device {} was unsuccessful.", id);
260 notificationHandler.onRemoteSchemaDown();
261 sourceRegistrations.forEach(Registration::close);
262 sourceRegistrations.clear();
265 private synchronized void setConnected(final boolean connected) {
266 this.connected = connected;
269 private ListenableFuture<SchemaResult> assembleSchemaContext(final DeviceSources deviceSources,
270 final NetconfSessionPreferences remoteSessionCapabilities) {
271 LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
273 sourceRegistrations.addAll(deviceSources.register(schemaRegistry));
275 return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
278 private ListenableFuture<@NonNull MountPointContext> createMountPointContext(
279 final EffectiveModelContext schemaContext, final BaseSchema baseSchema,
280 final NetconfDeviceCommunicator listener) {
281 final MountPointContext emptyContext = MountPointContext.of(schemaContext);
282 if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
283 return Futures.immediateFuture(emptyContext);
286 // Create a temporary RPC invoker and acquire the mount point tree
287 LOG.debug("{}: Acquiring available mount points", id);
288 final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
289 new NetconfMessageTransformer(emptyContext, false, baseSchema));
291 return Futures.transform(deviceRpc.domRpcService().invokeRpc(Get.QNAME, Builders.containerBuilder()
292 .withNodeIdentifier(NETCONF_GET_NODEID)
293 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
294 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
297 private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
298 final var errors = rpcResult.errors();
299 if (!errors.isEmpty()) {
300 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
302 final var schemaMounts = rpcResult.value();
303 if (schemaMounts == null) {
304 LOG.debug("{}: device does not define any schema mounts", id);
308 return DeviceMountPointContext.create(emptyContext, schemaMounts);
312 public void onRemoteSessionDown() {
313 cleanupInitialization();
314 salFacade.onDeviceDisconnected();
318 public void onNotification(final NetconfMessage notification) {
319 notificationHandler.handleNotification(notification);
322 private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
323 return notificationSupport ? baseSchemas.baseSchemaWithNotifications() : baseSchemas.baseSchema();
326 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
327 final RemoteDeviceCommunicator listener, final BaseSchema schema) {
328 return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
329 new NetconfMessageTransformer(result, true, schema));
333 * Just a transfer object containing schema related dependencies. Injected in constructor.
335 public static class SchemaResourcesDTO {
336 private final SchemaSourceRegistry schemaRegistry;
337 private final SchemaRepository schemaRepository;
338 private final EffectiveModelContextFactory schemaContextFactory;
339 private final NetconfDeviceSchemasResolver stateSchemasResolver;
341 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
342 final SchemaRepository schemaRepository,
343 final EffectiveModelContextFactory schemaContextFactory,
344 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
345 this.schemaRegistry = requireNonNull(schemaRegistry);
346 this.schemaRepository = requireNonNull(schemaRepository);
347 this.schemaContextFactory = requireNonNull(schemaContextFactory);
348 stateSchemasResolver = requireNonNull(deviceSchemasResolver);
351 public SchemaSourceRegistry getSchemaRegistry() {
352 return schemaRegistry;
355 public SchemaRepository getSchemaRepository() {
356 return schemaRepository;
359 public EffectiveModelContextFactory getSchemaContextFactory() {
360 return schemaContextFactory;
363 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
364 return stateSchemasResolver;
369 * A dedicated exception to indicate when we fail to setup an {@link EffectiveModelContext}.
371 public static final class EmptySchemaContextException extends Exception {
373 private static final long serialVersionUID = 1L;
375 public EmptySchemaContextException(final String message) {
381 * {@link NetconfDeviceCapabilities} and {@link EffectiveModelContext}.
383 private record SchemaResult(
384 @NonNull NetconfDeviceCapabilities capabilities,
385 @NonNull EffectiveModelContext modelContext) {
388 requireNonNull(capabilities);
389 requireNonNull(modelContext);
394 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
396 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
397 private final SettableFuture<SchemaResult> resultFuture = SettableFuture.create();
399 private final Set<AvailableCapability> nonModuleBasedCapabilities = new HashSet<>();
400 private final Map<QName, FailureReason> unresolvedCapabilites = new HashMap<>();
401 private final Set<AvailableCapability> resolvedCapabilities = new HashSet<>();
403 private final DeviceSources deviceSources;
404 private final NetconfSessionPreferences remoteSessionCapabilities;
406 private Collection<SourceIdentifier> requiredSources;
408 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
409 this.deviceSources = deviceSources;
410 this.remoteSessionCapabilities = remoteSessionCapabilities;
412 // If device supports notifications and does not contain necessary modules, add them automatically
413 if (remoteSessionCapabilities.containsNonModuleCapability(CapabilityURN.NOTIFICATION)) {
414 // FIXME: mutable collection modification!
415 deviceSources.getRequiredSourcesQName().addAll(List.of(
416 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
417 .$YangModuleInfoImpl.getInstance().getName(),
418 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
419 .$YangModuleInfoImpl.getInstance().getName())
423 requiredSources = deviceSources.getRequiredSources();
424 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
426 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
427 UnavailableCapability.FailureReason.MissingSource);
428 requiredSources.removeAll(missingSources);
431 ListenableFuture<SchemaResult> startResolution() {
437 public void onSuccess(final EffectiveModelContext result) {
438 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
440 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
441 unresolvedCapabilites.keySet());
442 resolvedCapabilities.addAll(filteredQNames.stream()
443 .map(capability -> new AvailableCapabilityBuilder()
444 .setCapability(capability.toString())
445 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
447 .collect(Collectors.toList()));
449 nonModuleBasedCapabilities.addAll(remoteSessionCapabilities.nonModuleCaps().keySet().stream()
450 .map(capability -> new AvailableCapabilityBuilder()
451 .setCapability(capability)
452 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
454 .collect(Collectors.toList()));
457 resultFuture.set(new SchemaResult(new NetconfDeviceCapabilities(ImmutableMap.copyOf(unresolvedCapabilites),
458 ImmutableSet.copyOf(resolvedCapabilities), ImmutableSet.copyOf(nonModuleBasedCapabilities)), result));
462 public void onFailure(final Throwable cause) {
463 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
464 // that might be wrapping a MissingSchemaSourceException so we need to look
465 // at the cause of the exception to make sure we don't misinterpret it.
466 if (cause instanceof MissingSchemaSourceException) {
467 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
468 } else if (cause instanceof SchemaResolutionException) {
469 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
471 LOG.debug("Unhandled failure", cause);
472 resultFuture.setException(cause);
480 private void trySetupSchema() {
481 if (!requiredSources.isEmpty()) {
482 // Initiate async resolution, drive it back based on the result
483 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
484 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
485 MoreExecutors.directExecutor());
487 LOG.debug("{}: no more sources for schema context", id);
488 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
492 private List<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
493 return origSources.parallelStream().filter(sourceIdentifier -> {
495 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
497 } catch (InterruptedException | ExecutionException e) {
500 }).collect(Collectors.toList());
503 private void addUnresolvedCapabilities(final Collection<QName> capabilities, final FailureReason reason) {
504 for (QName s : capabilities) {
505 unresolvedCapabilites.put(s, reason);
509 private List<SourceIdentifier> handleMissingSchemaSourceException(
510 final MissingSchemaSourceException exception) {
511 // In case source missing, try without it
512 final SourceIdentifier missingSource = exception.getSourceId();
513 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
515 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
516 id, missingSource, exception);
517 final var qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
518 if (!qNameOfMissingSource.isEmpty()) {
519 addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
521 return stripUnavailableSource(missingSource);
524 private Collection<SourceIdentifier> handleSchemaResolutionException(
525 final SchemaResolutionException resolutionException) {
526 // In case resolution error, try only with resolved sources
527 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
528 // FIXME Do we really have assurance that these two cases cannot happen at once?
529 if (resolutionException.getFailedSource() != null) {
530 // flawed model - exclude it
531 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
532 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
534 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
535 id, failedSourceId, resolutionException);
536 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(List.of(failedSourceId)),
537 UnavailableCapability.FailureReason.UnableToResolve);
538 return stripUnavailableSource(resolutionException.getFailedSource());
540 // unsatisfied imports
541 addUnresolvedCapabilities(
542 getQNameFromSourceIdentifiers(resolutionException.getUnsatisfiedImports().keySet()),
543 UnavailableCapability.FailureReason.UnableToResolve);
544 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
545 id, resolutionException.getUnsatisfiedImports());
546 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
547 id, resolutionException.getUnsatisfiedImports(), resolutionException);
548 return resolutionException.getResolvedSources();
551 private List<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
552 final var tmp = new ArrayList<>(requiredSources);
553 checkState(tmp.remove(sourceIdToRemove), "%s: Trying to remove %s from %s failed", id, sourceIdToRemove,
558 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
559 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
561 if (qNames.isEmpty()) {
562 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
565 return Collections2.filter(qNames, Predicates.notNull());
568 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
569 // Required sources are all required and provided merged in DeviceSourcesResolver
570 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
571 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
575 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
579 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
580 deviceSources.getRequiredSourcesQName());
581 // return null since we cannot find the QName,
582 // this capability will be removed from required sources and not reported as unresolved-capability