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.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;
32 import java.util.Objects;
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.netconf.api.NetconfMessage;
40 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
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.sal.connect.netconf.listener.NetconfDeviceCommunicator;
55 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.oper.available.capabilities.AvailableCapability;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.oper.available.capabilities.AvailableCapabilityBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.oper.unavailable.capabilities.UnavailableCapability;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.oper.unavailable.capabilities.UnavailableCapability.FailureReason;
61 import org.opendaylight.yangtools.concepts.Registration;
62 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
63 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
64 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
65 import org.opendaylight.yangtools.yang.common.QName;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
68 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
69 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
70 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
71 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
72 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
73 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
74 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
75 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
76 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
81 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
83 public class NetconfDevice implements RemoteDevice<NetconfDeviceCommunicator> {
84 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
86 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
87 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
88 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
89 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
91 protected final RemoteDeviceId id;
92 protected final EffectiveModelContextFactory schemaContextFactory;
93 protected final SchemaSourceRegistry schemaRegistry;
94 protected final SchemaRepository schemaRepository;
96 protected final List<Registration> sourceRegistrations = new ArrayList<>();
98 private final RemoteDeviceHandler salFacade;
99 private final ListeningExecutorService processingExecutor;
100 private final DeviceActionFactory deviceActionFactory;
101 private final NetconfDeviceSchemasResolver stateSchemasResolver;
102 private final NotificationHandler notificationHandler;
103 private final boolean reconnectOnSchemasChange;
104 private final BaseNetconfSchemas baseSchemas;
107 private boolean connected = false;
109 // Message transformer is constructed once the schemas are available
110 private NetconfMessageTransformer messageTransformer;
112 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
113 final RemoteDeviceId id, final RemoteDeviceHandler salFacade,
114 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
115 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
118 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
119 final RemoteDeviceId id, final RemoteDeviceHandler salFacade,
120 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
121 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 void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
137 final NetconfDeviceCommunicator listener) {
138 // SchemaContext setup has to be performed in a dedicated thread since
139 // we are in a netty thread in this method
140 // Yang models are being downloaded in this method and it would cause a
141 // deadlock if we used the netty thread
142 // http://netty.io/wiki/thread-model.html
144 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
146 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
147 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
148 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
149 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
150 new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
152 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
153 registerToBaseNetconfStream(initRpc, listener);
156 // Set up the SchemaContext for the device
157 final ListenableFuture<SchemaResult> futureSchema = Futures.transformAsync(sourceResolverFuture,
158 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
160 // Potentially acquire mount point list and interpret it
161 final ListenableFuture<NetconfDeviceSchema> futureContext = Futures.transformAsync(futureSchema,
162 result -> Futures.transform(createMountPointContext(result.modelContext(), baseSchema, listener),
163 mount -> new NetconfDeviceSchema(result.capabilities(), mount), processingExecutor),
166 Futures.addCallback(futureContext, new FutureCallback<>() {
168 public void onSuccess(final NetconfDeviceSchema result) {
169 handleSalInitializationSuccess(result, remoteSessionCapabilities,
170 getDeviceSpecificRpc(result.mountContext(), listener, baseSchema), listener);
174 public void onFailure(final Throwable cause) {
175 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
176 // FIXME: this causes salFacade to see onDeviceDisconnected() and then onDeviceFailed(), which is quite
178 handleSalInitializationFailure(cause, listener);
179 salFacade.onDeviceFailed(cause);
181 }, MoreExecutors.directExecutor());
184 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
185 final NetconfDeviceCommunicator listener) {
186 // TODO check whether the model describing create subscription is present in schema
187 // Perhaps add a default schema context to support create-subscription if the model was not provided
188 // (same as what we do for base netconf operations in transformer)
189 final var rpcResultListenableFuture = deviceRpc.invokeRpc(
190 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
191 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
193 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
195 public void onSuccess(final DOMRpcResult domRpcResult) {
196 notificationHandler.addNotificationFilter(notification -> {
197 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getIdentifier().getNodeType())) {
198 LOG.info("{}: Schemas change detected, reconnecting", id);
199 // Only disconnect is enough,
200 // the reconnecting nature of the connector will take care of reconnecting
201 listener.disconnect();
209 public void onFailure(final Throwable throwable) {
210 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
213 }, MoreExecutors.directExecutor());
216 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
217 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
220 private synchronized void handleSalInitializationSuccess(final NetconfDeviceSchema deviceSchema,
221 final NetconfSessionPreferences remoteSessionCapabilities, final Rpcs deviceRpc,
222 final RemoteDeviceCommunicator listener) {
223 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
224 //since salFacade.onDeviceDisconnected was already called.
226 final var mount = deviceSchema.mountContext();
227 messageTransformer = new NetconfMessageTransformer(mount, true,
228 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
230 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
231 salFacade.onDeviceConnected(deviceSchema, remoteSessionCapabilities,
232 new RemoteDeviceServices(deviceRpc, deviceActionFactory == null ? null
233 : deviceActionFactory.createDeviceAction(messageTransformer, listener)));
234 notificationHandler.onRemoteSchemaUp(messageTransformer);
236 LOG.info("{}: Netconf connector initialized successfully", id);
238 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
242 private void handleSalInitializationFailure(final Throwable throwable, final RemoteDeviceCommunicator listener) {
243 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
245 onRemoteSessionDown();
246 resetMessageTransformer();
250 * Set the transformer to null as is in initial state.
252 private void resetMessageTransformer() {
253 updateTransformer(null);
256 private synchronized void updateTransformer(final NetconfMessageTransformer transformer) {
257 messageTransformer = transformer;
260 private synchronized void setConnected(final boolean connected) {
261 this.connected = connected;
264 private ListenableFuture<SchemaResult> assembleSchemaContext(final DeviceSources deviceSources,
265 final NetconfSessionPreferences remoteSessionCapabilities) {
266 LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
268 sourceRegistrations.addAll(deviceSources.register(schemaRegistry));
270 return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
273 private ListenableFuture<@NonNull MountPointContext> createMountPointContext(
274 final EffectiveModelContext schemaContext, final BaseSchema baseSchema,
275 final NetconfDeviceCommunicator listener) {
276 final MountPointContext emptyContext = new EmptyMountPointContext(schemaContext);
277 if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
278 return Futures.immediateFuture(emptyContext);
281 // Create a temporary RPC invoker and acquire the mount point tree
282 LOG.debug("{}: Acquiring available mount points", id);
283 final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
284 new NetconfMessageTransformer(emptyContext, false, baseSchema));
286 return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
287 Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
288 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
289 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
292 private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
293 final var errors = rpcResult.errors();
294 if (!errors.isEmpty()) {
295 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
297 final var schemaMounts = rpcResult.value();
298 if (schemaMounts == null) {
299 LOG.debug("{}: device does not define any schema mounts", id);
303 return DeviceMountPointContext.create(emptyContext, schemaMounts);
307 public void onRemoteSessionDown() {
309 notificationHandler.onRemoteSchemaDown();
311 salFacade.onDeviceDisconnected();
312 sourceRegistrations.forEach(Registration::close);
313 sourceRegistrations.clear();
314 resetMessageTransformer();
318 public void onRemoteSessionFailed(final Throwable throwable) {
320 salFacade.onDeviceFailed(throwable);
324 public void onNotification(final NetconfMessage notification) {
325 notificationHandler.handleNotification(notification);
328 private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
329 return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
332 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
333 final RemoteDeviceCommunicator listener, final BaseSchema schema) {
334 return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
335 new NetconfMessageTransformer(result, true, schema));
339 * Just a transfer object containing schema related dependencies. Injected in constructor.
341 public static class SchemaResourcesDTO {
342 private final SchemaSourceRegistry schemaRegistry;
343 private final SchemaRepository schemaRepository;
344 private final EffectiveModelContextFactory schemaContextFactory;
345 private final NetconfDeviceSchemasResolver stateSchemasResolver;
347 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
348 final SchemaRepository schemaRepository,
349 final EffectiveModelContextFactory schemaContextFactory,
350 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
351 this.schemaRegistry = requireNonNull(schemaRegistry);
352 this.schemaRepository = requireNonNull(schemaRepository);
353 this.schemaContextFactory = requireNonNull(schemaContextFactory);
354 stateSchemasResolver = requireNonNull(deviceSchemasResolver);
357 public SchemaSourceRegistry getSchemaRegistry() {
358 return schemaRegistry;
361 public SchemaRepository getSchemaRepository() {
362 return schemaRepository;
365 public EffectiveModelContextFactory getSchemaContextFactory() {
366 return schemaContextFactory;
369 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
370 return stateSchemasResolver;
375 * A dedicated exception to indicate when we fail to setup an {@link EffectiveModelContext}.
377 public static final class EmptySchemaContextException extends Exception {
378 private static final long serialVersionUID = 1L;
380 public EmptySchemaContextException(final String message) {
386 * {@link NetconfDeviceCapabilities} and {@link EffectiveModelContext}.
388 private record SchemaResult(
389 @NonNull NetconfDeviceCapabilities capabilities,
390 @NonNull EffectiveModelContext modelContext) {
393 requireNonNull(capabilities);
394 requireNonNull(modelContext);
399 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
401 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
402 private final SettableFuture<SchemaResult> resultFuture = SettableFuture.create();
404 private final Set<AvailableCapability> nonModuleBasedCapabilities = new HashSet<>();
405 private final Map<QName, FailureReason> unresolvedCapabilites = new HashMap<>();
406 private final Set<AvailableCapability> resolvedCapabilities = new HashSet<>();
408 private final DeviceSources deviceSources;
409 private final NetconfSessionPreferences remoteSessionCapabilities;
411 private Collection<SourceIdentifier> requiredSources;
413 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
414 this.deviceSources = deviceSources;
415 this.remoteSessionCapabilities = remoteSessionCapabilities;
417 // If device supports notifications and does not contain necessary modules, add them automatically
418 if (remoteSessionCapabilities.containsNonModuleCapability(
419 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0)) {
420 deviceSources.getRequiredSourcesQName().addAll(
422 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
423 .$YangModuleInfoImpl.getInstance().getName(),
424 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
425 .$YangModuleInfoImpl.getInstance().getName()
430 requiredSources = deviceSources.getRequiredSources();
431 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
433 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
434 UnavailableCapability.FailureReason.MissingSource);
435 requiredSources.removeAll(missingSources);
438 ListenableFuture<SchemaResult> startResolution() {
444 public void onSuccess(final EffectiveModelContext result) {
445 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
447 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
448 unresolvedCapabilites.keySet());
449 resolvedCapabilities.addAll(filteredQNames.stream()
450 .map(capability -> new AvailableCapabilityBuilder()
451 .setCapability(capability.toString())
452 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
454 .collect(Collectors.toList()));
456 nonModuleBasedCapabilities.addAll(remoteSessionCapabilities.nonModuleCaps().keySet().stream()
457 .map(capability -> new AvailableCapabilityBuilder()
458 .setCapability(capability)
459 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
461 .collect(Collectors.toList()));
464 resultFuture.set(new SchemaResult(new NetconfDeviceCapabilities(ImmutableMap.copyOf(unresolvedCapabilites),
465 ImmutableSet.copyOf(resolvedCapabilities), ImmutableSet.copyOf(nonModuleBasedCapabilities)), result));
469 public void onFailure(final Throwable cause) {
470 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
471 // that might be wrapping a MissingSchemaSourceException so we need to look
472 // at the cause of the exception to make sure we don't misinterpret it.
473 if (cause instanceof MissingSchemaSourceException) {
474 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
475 } else if (cause instanceof SchemaResolutionException) {
476 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
478 LOG.debug("Unhandled failure", cause);
479 resultFuture.setException(cause);
487 private void trySetupSchema() {
488 if (!requiredSources.isEmpty()) {
489 // Initiate async resolution, drive it back based on the result
490 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
491 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
492 MoreExecutors.directExecutor());
494 LOG.debug("{}: no more sources for schema context", id);
495 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
499 private List<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
500 return origSources.parallelStream().filter(sourceIdentifier -> {
502 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
504 } catch (InterruptedException | ExecutionException e) {
507 }).collect(Collectors.toList());
510 private void addUnresolvedCapabilities(final Collection<QName> capabilities, final FailureReason reason) {
511 for (QName s : capabilities) {
512 unresolvedCapabilites.put(s, reason);
516 private List<SourceIdentifier> handleMissingSchemaSourceException(
517 final MissingSchemaSourceException exception) {
518 // In case source missing, try without it
519 final SourceIdentifier missingSource = exception.getSourceId();
520 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
522 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
523 id, missingSource, exception);
524 final var qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
525 if (!qNameOfMissingSource.isEmpty()) {
526 addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
528 return stripUnavailableSource(missingSource);
531 private Collection<SourceIdentifier> handleSchemaResolutionException(
532 final SchemaResolutionException resolutionException) {
533 // In case resolution error, try only with resolved sources
534 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
535 // FIXME Do we really have assurance that these two cases cannot happen at once?
536 if (resolutionException.getFailedSource() != null) {
537 // flawed model - exclude it
538 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
539 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
541 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
542 id, failedSourceId, resolutionException);
543 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(List.of(failedSourceId)),
544 UnavailableCapability.FailureReason.UnableToResolve);
545 return stripUnavailableSource(resolutionException.getFailedSource());
547 // unsatisfied imports
548 addUnresolvedCapabilities(
549 getQNameFromSourceIdentifiers(resolutionException.getUnsatisfiedImports().keySet()),
550 UnavailableCapability.FailureReason.UnableToResolve);
551 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
552 id, resolutionException.getUnsatisfiedImports());
553 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
554 id, resolutionException.getUnsatisfiedImports(), resolutionException);
555 return resolutionException.getResolvedSources();
558 private List<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
559 final var tmp = new ArrayList<>(requiredSources);
560 checkState(tmp.remove(sourceIdToRemove), "%s: Trying to remove %s from %s failed", id, sourceIdToRemove,
565 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
566 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
568 if (qNames.isEmpty()) {
569 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
572 return Collections2.filter(qNames, Predicates.notNull());
575 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
576 // Required sources are all required and provided merged in DeviceSourcesResolver
577 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
578 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
582 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
586 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
587 deviceSources.getRequiredSourcesQName());
588 // return null since we cannot find the QName,
589 // this capability will be removed from required sources and not reported as unresolved-capability