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.ExecutionException;
34 import java.util.concurrent.Executor;
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.netconf.api.CapabilityURN;
40 import org.opendaylight.netconf.api.NetconfMessage;
41 import org.opendaylight.netconf.client.mdsal.api.BaseNetconfSchemas;
42 import org.opendaylight.netconf.client.mdsal.api.DeviceActionFactory;
43 import org.opendaylight.netconf.client.mdsal.api.NetconfDeviceSchemasResolver;
44 import org.opendaylight.netconf.client.mdsal.api.NetconfSessionPreferences;
45 import org.opendaylight.netconf.client.mdsal.api.RemoteDevice;
46 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceCommunicator;
47 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceHandler;
48 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
49 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices;
50 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices.Rpcs;
51 import org.opendaylight.netconf.client.mdsal.impl.BaseSchema;
52 import org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil;
53 import org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformer;
54 import org.opendaylight.netconf.client.mdsal.spi.NetconfDeviceRpc;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.oper.available.capabilities.AvailableCapability;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.oper.available.capabilities.AvailableCapabilityBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.oper.unavailable.capabilities.UnavailableCapability;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.oper.unavailable.capabilities.UnavailableCapability.FailureReason;
60 import org.opendaylight.yangtools.concepts.Registration;
61 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
62 import org.opendaylight.yangtools.yang.common.QName;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.schema.MountPointContext;
66 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
67 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
68 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
69 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
70 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
71 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
72 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
73 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
74 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
79 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
81 public class NetconfDevice implements RemoteDevice<NetconfDeviceCommunicator> {
82 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
84 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
85 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
86 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.of(
87 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
89 protected final RemoteDeviceId id;
90 protected final EffectiveModelContextFactory schemaContextFactory;
91 protected final SchemaSourceRegistry schemaRegistry;
92 protected final SchemaRepository schemaRepository;
94 protected final List<Registration> sourceRegistrations = new ArrayList<>();
96 private final RemoteDeviceHandler salFacade;
97 private final Executor processingExecutor;
98 private final DeviceActionFactory deviceActionFactory;
99 private final NetconfDeviceSchemasResolver stateSchemasResolver;
100 private final NotificationHandler notificationHandler;
101 private final boolean reconnectOnSchemasChange;
102 private final BaseNetconfSchemas baseSchemas;
105 private boolean connected = false;
107 // Message transformer is constructed once the schemas are available
108 private NetconfMessageTransformer messageTransformer;
110 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
111 final RemoteDeviceId id, final RemoteDeviceHandler salFacade, final Executor globalProcessingExecutor,
112 final boolean reconnectOnSchemasChange) {
113 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
116 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
117 final RemoteDeviceId id, final RemoteDeviceHandler salFacade, final Executor globalProcessingExecutor,
118 final boolean reconnectOnSchemasChange, final DeviceActionFactory deviceActionFactory) {
119 this.baseSchemas = requireNonNull(baseSchemas);
121 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
122 this.deviceActionFactory = deviceActionFactory;
123 schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
124 schemaRepository = schemaResourcesDTO.getSchemaRepository();
125 schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
126 this.salFacade = salFacade;
127 stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
128 processingExecutor = requireNonNull(globalProcessingExecutor);
129 notificationHandler = new NotificationHandler(salFacade, id);
133 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
134 final NetconfDeviceCommunicator listener) {
135 // SchemaContext setup has to be performed in a dedicated thread since
136 // we are in a netty thread in this method
137 // Yang models are being downloaded in this method and it would cause a
138 // deadlock if we used the netty thread
139 // http://netty.io/wiki/thread-model.html
141 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
143 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
144 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
145 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
146 final ListenableFuture<DeviceSources> sourceResolverFuture = Futures.submit(
147 new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver),
150 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
151 registerToBaseNetconfStream(initRpc, listener);
154 // Set up the SchemaContext for the device
155 final ListenableFuture<SchemaResult> futureSchema = Futures.transformAsync(sourceResolverFuture,
156 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
158 // Potentially acquire mount point list and interpret it
159 final ListenableFuture<NetconfDeviceSchema> futureContext = Futures.transformAsync(futureSchema,
160 result -> Futures.transform(createMountPointContext(result.modelContext(), baseSchema, listener),
161 mount -> new NetconfDeviceSchema(result.capabilities(), mount), processingExecutor),
164 Futures.addCallback(futureContext, new FutureCallback<>() {
166 public void onSuccess(final NetconfDeviceSchema result) {
167 handleSalInitializationSuccess(result, remoteSessionCapabilities,
168 getDeviceSpecificRpc(result.mountContext(), listener, baseSchema), listener);
172 public void onFailure(final Throwable cause) {
173 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
174 // FIXME: this causes salFacade to see onDeviceDisconnected() and then onDeviceFailed(), which is quite
176 handleSalInitializationFailure(cause, listener);
177 salFacade.onDeviceFailed(cause);
179 }, MoreExecutors.directExecutor());
182 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
183 final NetconfDeviceCommunicator listener) {
184 // TODO check whether the model describing create subscription is present in schema
185 // Perhaps add a default schema context to support create-subscription if the model was not provided
186 // (same as what we do for base netconf operations in transformer)
187 final var rpcResultListenableFuture = deviceRpc.invokeRpc(
188 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
189 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
191 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
193 public void onSuccess(final DOMRpcResult domRpcResult) {
194 notificationHandler.addNotificationFilter(notification -> {
195 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getIdentifier().getNodeType())) {
196 LOG.info("{}: Schemas change detected, reconnecting", id);
197 // Only disconnect is enough,
198 // the reconnecting nature of the connector will take care of reconnecting
199 listener.disconnect();
207 public void onFailure(final Throwable throwable) {
208 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
211 }, MoreExecutors.directExecutor());
214 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
215 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
218 private synchronized void handleSalInitializationSuccess(final NetconfDeviceSchema deviceSchema,
219 final NetconfSessionPreferences remoteSessionCapabilities, final Rpcs deviceRpc,
220 final RemoteDeviceCommunicator listener) {
221 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
222 //since salFacade.onDeviceDisconnected was already called.
224 final var mount = deviceSchema.mountContext();
225 messageTransformer = new NetconfMessageTransformer(mount, true,
226 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
228 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
229 salFacade.onDeviceConnected(deviceSchema, remoteSessionCapabilities,
230 new RemoteDeviceServices(deviceRpc, deviceActionFactory == null ? null
231 : deviceActionFactory.createDeviceAction(messageTransformer, listener)));
232 notificationHandler.onRemoteSchemaUp(messageTransformer);
234 LOG.info("{}: Netconf connector initialized successfully", id);
236 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
240 private void handleSalInitializationFailure(final Throwable throwable, final RemoteDeviceCommunicator listener) {
241 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
243 onRemoteSessionDown();
244 resetMessageTransformer();
248 * Set the transformer to null as is in initial state.
250 private void resetMessageTransformer() {
251 updateTransformer(null);
254 private synchronized void updateTransformer(final NetconfMessageTransformer transformer) {
255 messageTransformer = transformer;
258 private synchronized void setConnected(final boolean connected) {
259 this.connected = connected;
262 private ListenableFuture<SchemaResult> assembleSchemaContext(final DeviceSources deviceSources,
263 final NetconfSessionPreferences remoteSessionCapabilities) {
264 LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
266 sourceRegistrations.addAll(deviceSources.register(schemaRegistry));
268 return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
271 private ListenableFuture<@NonNull MountPointContext> createMountPointContext(
272 final EffectiveModelContext schemaContext, final BaseSchema baseSchema,
273 final NetconfDeviceCommunicator listener) {
274 final MountPointContext emptyContext = MountPointContext.of(schemaContext);
275 if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
276 return Futures.immediateFuture(emptyContext);
279 // Create a temporary RPC invoker and acquire the mount point tree
280 LOG.debug("{}: Acquiring available mount points", id);
281 final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
282 new NetconfMessageTransformer(emptyContext, false, baseSchema));
284 return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
285 Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
286 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
287 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
290 private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
291 final var errors = rpcResult.errors();
292 if (!errors.isEmpty()) {
293 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
295 final var schemaMounts = rpcResult.value();
296 if (schemaMounts == null) {
297 LOG.debug("{}: device does not define any schema mounts", id);
301 return DeviceMountPointContext.create(emptyContext, schemaMounts);
305 public void onRemoteSessionDown() {
307 notificationHandler.onRemoteSchemaDown();
309 salFacade.onDeviceDisconnected();
310 sourceRegistrations.forEach(Registration::close);
311 sourceRegistrations.clear();
312 resetMessageTransformer();
316 public void onRemoteSessionFailed(final Throwable throwable) {
318 salFacade.onDeviceFailed(throwable);
322 public void onNotification(final NetconfMessage notification) {
323 notificationHandler.handleNotification(notification);
326 private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
327 return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
330 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
331 final RemoteDeviceCommunicator listener, final BaseSchema schema) {
332 return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
333 new NetconfMessageTransformer(result, true, schema));
337 * Just a transfer object containing schema related dependencies. Injected in constructor.
339 public static class SchemaResourcesDTO {
340 private final SchemaSourceRegistry schemaRegistry;
341 private final SchemaRepository schemaRepository;
342 private final EffectiveModelContextFactory schemaContextFactory;
343 private final NetconfDeviceSchemasResolver stateSchemasResolver;
345 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
346 final SchemaRepository schemaRepository,
347 final EffectiveModelContextFactory schemaContextFactory,
348 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
349 this.schemaRegistry = requireNonNull(schemaRegistry);
350 this.schemaRepository = requireNonNull(schemaRepository);
351 this.schemaContextFactory = requireNonNull(schemaContextFactory);
352 stateSchemasResolver = requireNonNull(deviceSchemasResolver);
355 public SchemaSourceRegistry getSchemaRegistry() {
356 return schemaRegistry;
359 public SchemaRepository getSchemaRepository() {
360 return schemaRepository;
363 public EffectiveModelContextFactory getSchemaContextFactory() {
364 return schemaContextFactory;
367 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
368 return stateSchemasResolver;
373 * A dedicated exception to indicate when we fail to setup an {@link EffectiveModelContext}.
375 public static final class EmptySchemaContextException extends Exception {
377 private static final long serialVersionUID = 1L;
379 public EmptySchemaContextException(final String message) {
385 * {@link NetconfDeviceCapabilities} and {@link EffectiveModelContext}.
387 private record SchemaResult(
388 @NonNull NetconfDeviceCapabilities capabilities,
389 @NonNull EffectiveModelContext modelContext) {
392 requireNonNull(capabilities);
393 requireNonNull(modelContext);
398 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
400 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
401 private final SettableFuture<SchemaResult> resultFuture = SettableFuture.create();
403 private final Set<AvailableCapability> nonModuleBasedCapabilities = new HashSet<>();
404 private final Map<QName, FailureReason> unresolvedCapabilites = new HashMap<>();
405 private final Set<AvailableCapability> resolvedCapabilities = new HashSet<>();
407 private final DeviceSources deviceSources;
408 private final NetconfSessionPreferences remoteSessionCapabilities;
410 private Collection<SourceIdentifier> requiredSources;
412 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
413 this.deviceSources = deviceSources;
414 this.remoteSessionCapabilities = remoteSessionCapabilities;
416 // If device supports notifications and does not contain necessary modules, add them automatically
417 if (remoteSessionCapabilities.containsNonModuleCapability(CapabilityURN.NOTIFICATION)) {
418 // FIXME: mutable collection modification!
419 deviceSources.getRequiredSourcesQName().addAll(List.of(
420 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
421 .$YangModuleInfoImpl.getInstance().getName(),
422 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
423 .$YangModuleInfoImpl.getInstance().getName())
427 requiredSources = deviceSources.getRequiredSources();
428 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
430 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
431 UnavailableCapability.FailureReason.MissingSource);
432 requiredSources.removeAll(missingSources);
435 ListenableFuture<SchemaResult> startResolution() {
441 public void onSuccess(final EffectiveModelContext result) {
442 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
444 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
445 unresolvedCapabilites.keySet());
446 resolvedCapabilities.addAll(filteredQNames.stream()
447 .map(capability -> new AvailableCapabilityBuilder()
448 .setCapability(capability.toString())
449 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
451 .collect(Collectors.toList()));
453 nonModuleBasedCapabilities.addAll(remoteSessionCapabilities.nonModuleCaps().keySet().stream()
454 .map(capability -> new AvailableCapabilityBuilder()
455 .setCapability(capability)
456 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
458 .collect(Collectors.toList()));
461 resultFuture.set(new SchemaResult(new NetconfDeviceCapabilities(ImmutableMap.copyOf(unresolvedCapabilites),
462 ImmutableSet.copyOf(resolvedCapabilities), ImmutableSet.copyOf(nonModuleBasedCapabilities)), result));
466 public void onFailure(final Throwable cause) {
467 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
468 // that might be wrapping a MissingSchemaSourceException so we need to look
469 // at the cause of the exception to make sure we don't misinterpret it.
470 if (cause instanceof MissingSchemaSourceException) {
471 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
472 } else if (cause instanceof SchemaResolutionException) {
473 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
475 LOG.debug("Unhandled failure", cause);
476 resultFuture.setException(cause);
484 private void trySetupSchema() {
485 if (!requiredSources.isEmpty()) {
486 // Initiate async resolution, drive it back based on the result
487 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
488 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
489 MoreExecutors.directExecutor());
491 LOG.debug("{}: no more sources for schema context", id);
492 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
496 private List<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
497 return origSources.parallelStream().filter(sourceIdentifier -> {
499 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
501 } catch (InterruptedException | ExecutionException e) {
504 }).collect(Collectors.toList());
507 private void addUnresolvedCapabilities(final Collection<QName> capabilities, final FailureReason reason) {
508 for (QName s : capabilities) {
509 unresolvedCapabilites.put(s, reason);
513 private List<SourceIdentifier> handleMissingSchemaSourceException(
514 final MissingSchemaSourceException exception) {
515 // In case source missing, try without it
516 final SourceIdentifier missingSource = exception.getSourceId();
517 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
519 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
520 id, missingSource, exception);
521 final var qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
522 if (!qNameOfMissingSource.isEmpty()) {
523 addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
525 return stripUnavailableSource(missingSource);
528 private Collection<SourceIdentifier> handleSchemaResolutionException(
529 final SchemaResolutionException resolutionException) {
530 // In case resolution error, try only with resolved sources
531 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
532 // FIXME Do we really have assurance that these two cases cannot happen at once?
533 if (resolutionException.getFailedSource() != null) {
534 // flawed model - exclude it
535 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
536 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
538 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
539 id, failedSourceId, resolutionException);
540 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(List.of(failedSourceId)),
541 UnavailableCapability.FailureReason.UnableToResolve);
542 return stripUnavailableSource(resolutionException.getFailedSource());
544 // unsatisfied imports
545 addUnresolvedCapabilities(
546 getQNameFromSourceIdentifiers(resolutionException.getUnsatisfiedImports().keySet()),
547 UnavailableCapability.FailureReason.UnableToResolve);
548 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
549 id, resolutionException.getUnsatisfiedImports());
550 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
551 id, resolutionException.getUnsatisfiedImports(), resolutionException);
552 return resolutionException.getResolvedSources();
555 private List<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
556 final var tmp = new ArrayList<>(requiredSources);
557 checkState(tmp.remove(sourceIdToRemove), "%s: Trying to remove %s from %s failed", id, sourceIdToRemove,
562 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
563 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
565 if (qNames.isEmpty()) {
566 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
569 return Collections2.filter(qNames, Predicates.notNull());
572 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
573 // Required sources are all required and provided merged in DeviceSourcesResolver
574 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
575 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
579 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
583 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
584 deviceSources.getRequiredSourcesQName());
585 // return null since we cannot find the QName,
586 // this capability will be removed from required sources and not reported as unresolved-capability