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.sal.connect.netconf;
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
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.sal.connect.api.DeviceActionFactory;
42 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
43 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
44 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
45 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
46 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
47 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceServices;
48 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceServices.Rpcs;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
50 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
51 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
52 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
53 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseNetconfSchemas;
54 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
55 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
56 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
57 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability.FailureReason;
63 import org.opendaylight.yangtools.concepts.Registration;
64 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
65 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
66 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
67 import org.opendaylight.yangtools.yang.common.QName;
68 import org.opendaylight.yangtools.yang.common.RpcError;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
71 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
73 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
74 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
75 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
76 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
77 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
78 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
79 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
80 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
81 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
86 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
88 public class NetconfDevice implements RemoteDevice<NetconfDeviceCommunicator> {
89 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
91 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
92 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
93 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
94 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
96 protected final RemoteDeviceId id;
97 protected final EffectiveModelContextFactory schemaContextFactory;
98 protected final SchemaSourceRegistry schemaRegistry;
99 protected final SchemaRepository schemaRepository;
101 protected final List<Registration> sourceRegistrations = new ArrayList<>();
103 private final RemoteDeviceHandler salFacade;
104 private final ListeningExecutorService processingExecutor;
105 private final DeviceActionFactory deviceActionFactory;
106 private final NetconfDeviceSchemasResolver stateSchemasResolver;
107 private final NotificationHandler notificationHandler;
108 private final boolean reconnectOnSchemasChange;
109 private final BaseNetconfSchemas baseSchemas;
112 private boolean connected = false;
114 // Message transformer is constructed once the schemas are available
115 private MessageTransformer messageTransformer;
117 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
118 final RemoteDeviceId id, final RemoteDeviceHandler salFacade,
119 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
120 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
123 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
124 final RemoteDeviceId id, final RemoteDeviceHandler salFacade,
125 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
126 final DeviceActionFactory deviceActionFactory) {
127 this.baseSchemas = requireNonNull(baseSchemas);
129 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
130 this.deviceActionFactory = deviceActionFactory;
131 schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
132 schemaRepository = schemaResourcesDTO.getSchemaRepository();
133 schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
134 this.salFacade = salFacade;
135 stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
136 processingExecutor = requireNonNull(globalProcessingExecutor);
137 notificationHandler = new NotificationHandler(salFacade, id);
141 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
142 final NetconfDeviceCommunicator listener) {
143 // SchemaContext setup has to be performed in a dedicated thread since
144 // we are in a netty thread in this method
145 // Yang models are being downloaded in this method and it would cause a
146 // deadlock if we used the netty thread
147 // http://netty.io/wiki/thread-model.html
149 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
151 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
152 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
153 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
154 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
155 new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
157 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
158 registerToBaseNetconfStream(initRpc, listener);
161 // Set up the SchemaContext for the device
162 final ListenableFuture<SchemaResult> futureSchema = Futures.transformAsync(sourceResolverFuture,
163 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
165 // Potentially acquire mount point list and interpret it
166 final ListenableFuture<NetconfDeviceSchema> futureContext = Futures.transformAsync(futureSchema,
167 result -> Futures.transform(createMountPointContext(result.modelContext(), baseSchema, listener),
168 mount -> new NetconfDeviceSchema(result.capabilities(), mount), processingExecutor),
171 Futures.addCallback(futureContext, new FutureCallback<>() {
173 public void onSuccess(final NetconfDeviceSchema result) {
174 handleSalInitializationSuccess(result, remoteSessionCapabilities,
175 getDeviceSpecificRpc(result.mountContext(), listener, baseSchema), listener);
179 public void onFailure(final Throwable cause) {
180 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
181 // FIXME: this causes salFacade to see onDeviceDisconnected() and then onDeviceFailed(), which is quite
183 handleSalInitializationFailure(cause, listener);
184 salFacade.onDeviceFailed(cause);
186 }, MoreExecutors.directExecutor());
189 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
190 final NetconfDeviceCommunicator listener) {
191 // TODO check whether the model describing create subscription is present in schema
192 // Perhaps add a default schema context to support create-subscription if the model was not provided
193 // (same as what we do for base netconf operations in transformer)
194 final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
195 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
196 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
198 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
200 public void onSuccess(final DOMRpcResult domRpcResult) {
201 notificationHandler.addNotificationFilter(notification -> {
202 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getIdentifier().getNodeType())) {
203 LOG.info("{}: Schemas change detected, reconnecting", id);
204 // Only disconnect is enough,
205 // the reconnecting nature of the connector will take care of reconnecting
206 listener.disconnect();
214 public void onFailure(final Throwable throwable) {
215 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
218 }, MoreExecutors.directExecutor());
221 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
222 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
225 private synchronized void handleSalInitializationSuccess(final NetconfDeviceSchema deviceSchema,
226 final NetconfSessionPreferences remoteSessionCapabilities, final Rpcs deviceRpc,
227 final RemoteDeviceCommunicator listener) {
228 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
229 //since salFacade.onDeviceDisconnected was already called.
231 final var mount = deviceSchema.mountContext();
232 messageTransformer = new NetconfMessageTransformer(mount, true,
233 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
235 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
236 salFacade.onDeviceConnected(deviceSchema, remoteSessionCapabilities,
237 new RemoteDeviceServices(deviceRpc, deviceActionFactory == null ? null
238 : deviceActionFactory.createDeviceAction(messageTransformer, listener)));
239 notificationHandler.onRemoteSchemaUp(messageTransformer);
241 LOG.info("{}: Netconf connector initialized successfully", id);
243 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
247 private void handleSalInitializationFailure(final Throwable throwable, final RemoteDeviceCommunicator listener) {
248 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
250 onRemoteSessionDown();
251 resetMessageTransformer();
255 * Set the transformer to null as is in initial state.
257 private void resetMessageTransformer() {
258 updateTransformer(null);
261 private synchronized void updateTransformer(final MessageTransformer transformer) {
262 messageTransformer = transformer;
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 = new EmptyMountPointContext(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.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
292 Builders.containerBuilder().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 Collection<? extends RpcError> errors = rpcResult.getErrors();
299 if (!errors.isEmpty()) {
300 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
302 final NormalizedNode schemaMounts = rpcResult.getResult();
303 if (schemaMounts == null) {
304 LOG.debug("{}: device does not define any schema mounts", id);
307 if (!(schemaMounts instanceof ContainerNode)) {
308 LOG.warn("{}: ignoring non-container schema mounts {}", id, schemaMounts);
312 return DeviceMountPointContext.create(emptyContext, (ContainerNode) schemaMounts);
316 public void onRemoteSessionDown() {
318 notificationHandler.onRemoteSchemaDown();
320 salFacade.onDeviceDisconnected();
321 sourceRegistrations.forEach(Registration::close);
322 sourceRegistrations.clear();
323 resetMessageTransformer();
327 public void onRemoteSessionFailed(final Throwable throwable) {
329 salFacade.onDeviceFailed(throwable);
333 public void onNotification(final NetconfMessage notification) {
334 notificationHandler.handleNotification(notification);
337 private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
338 return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
341 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
342 final RemoteDeviceCommunicator listener, final BaseSchema schema) {
343 return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
344 new NetconfMessageTransformer(result, true, schema));
348 * Just a transfer object containing schema related dependencies. Injected in constructor.
350 public static class SchemaResourcesDTO {
351 private final SchemaSourceRegistry schemaRegistry;
352 private final SchemaRepository schemaRepository;
353 private final EffectiveModelContextFactory schemaContextFactory;
354 private final NetconfDeviceSchemasResolver stateSchemasResolver;
356 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
357 final SchemaRepository schemaRepository,
358 final EffectiveModelContextFactory schemaContextFactory,
359 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
360 this.schemaRegistry = requireNonNull(schemaRegistry);
361 this.schemaRepository = requireNonNull(schemaRepository);
362 this.schemaContextFactory = requireNonNull(schemaContextFactory);
363 stateSchemasResolver = requireNonNull(deviceSchemasResolver);
366 public SchemaSourceRegistry getSchemaRegistry() {
367 return schemaRegistry;
370 public SchemaRepository getSchemaRepository() {
371 return schemaRepository;
374 public EffectiveModelContextFactory getSchemaContextFactory() {
375 return schemaContextFactory;
378 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
379 return stateSchemasResolver;
384 * A dedicated exception to indicate when we fail to setup an {@link EffectiveModelContext}.
386 public static final class EmptySchemaContextException extends Exception {
387 private static final long serialVersionUID = 1L;
389 public EmptySchemaContextException(final String message) {
395 * {@link NetconfDeviceCapabilities} and {@link EffectiveModelContext}.
397 private record SchemaResult(
398 @NonNull NetconfDeviceCapabilities capabilities,
399 @NonNull EffectiveModelContext modelContext) {
402 requireNonNull(capabilities);
403 requireNonNull(modelContext);
408 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
410 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
411 private final SettableFuture<SchemaResult> resultFuture = SettableFuture.create();
413 private final Set<AvailableCapability> nonModuleBasedCapabilities = new HashSet<>();
414 private final Map<QName, FailureReason> unresolvedCapabilites = new HashMap<>();
415 private final Set<AvailableCapability> resolvedCapabilities = new HashSet<>();
417 private final DeviceSources deviceSources;
418 private final NetconfSessionPreferences remoteSessionCapabilities;
420 private Collection<SourceIdentifier> requiredSources;
422 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
423 this.deviceSources = deviceSources;
424 this.remoteSessionCapabilities = remoteSessionCapabilities;
426 // If device supports notifications and does not contain necessary modules, add them automatically
427 if (remoteSessionCapabilities.containsNonModuleCapability(
428 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0)) {
429 deviceSources.getRequiredSourcesQName().addAll(
431 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
432 .$YangModuleInfoImpl.getInstance().getName(),
433 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
434 .$YangModuleInfoImpl.getInstance().getName()
439 requiredSources = deviceSources.getRequiredSources();
440 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
442 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
443 UnavailableCapability.FailureReason.MissingSource);
444 requiredSources.removeAll(missingSources);
447 ListenableFuture<SchemaResult> startResolution() {
453 public void onSuccess(final EffectiveModelContext result) {
454 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
456 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
457 unresolvedCapabilites.keySet());
458 resolvedCapabilities.addAll(filteredQNames.stream()
459 .map(capability -> new AvailableCapabilityBuilder()
460 .setCapability(capability.toString())
461 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
463 .collect(Collectors.toList()));
465 nonModuleBasedCapabilities.addAll(remoteSessionCapabilities.nonModuleCaps().keySet().stream()
466 .map(capability -> new AvailableCapabilityBuilder()
467 .setCapability(capability)
468 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
470 .collect(Collectors.toList()));
473 resultFuture.set(new SchemaResult(new NetconfDeviceCapabilities(ImmutableMap.copyOf(unresolvedCapabilites),
474 ImmutableSet.copyOf(resolvedCapabilities), ImmutableSet.copyOf(nonModuleBasedCapabilities)), result));
478 public void onFailure(final Throwable cause) {
479 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
480 // that might be wrapping a MissingSchemaSourceException so we need to look
481 // at the cause of the exception to make sure we don't misinterpret it.
482 if (cause instanceof MissingSchemaSourceException) {
483 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
484 } else if (cause instanceof SchemaResolutionException) {
485 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
487 LOG.debug("Unhandled failure", cause);
488 resultFuture.setException(cause);
496 private void trySetupSchema() {
497 if (!requiredSources.isEmpty()) {
498 // Initiate async resolution, drive it back based on the result
499 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
500 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
501 MoreExecutors.directExecutor());
503 LOG.debug("{}: no more sources for schema context", id);
504 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
508 private List<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
509 return origSources.parallelStream().filter(sourceIdentifier -> {
511 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
513 } catch (InterruptedException | ExecutionException e) {
516 }).collect(Collectors.toList());
519 private void addUnresolvedCapabilities(final Collection<QName> capabilities, final FailureReason reason) {
520 for (QName s : capabilities) {
521 unresolvedCapabilites.put(s, reason);
525 private List<SourceIdentifier> handleMissingSchemaSourceException(
526 final MissingSchemaSourceException exception) {
527 // In case source missing, try without it
528 final SourceIdentifier missingSource = exception.getSourceId();
529 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
531 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
532 id, missingSource, exception);
533 final var qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
534 if (!qNameOfMissingSource.isEmpty()) {
535 addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
537 return stripUnavailableSource(missingSource);
540 private Collection<SourceIdentifier> handleSchemaResolutionException(
541 final SchemaResolutionException resolutionException) {
542 // In case resolution error, try only with resolved sources
543 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
544 // FIXME Do we really have assurance that these two cases cannot happen at once?
545 if (resolutionException.getFailedSource() != null) {
546 // flawed model - exclude it
547 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
548 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
550 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
551 id, failedSourceId, resolutionException);
552 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(List.of(failedSourceId)),
553 UnavailableCapability.FailureReason.UnableToResolve);
554 return stripUnavailableSource(resolutionException.getFailedSource());
556 // unsatisfied imports
557 addUnresolvedCapabilities(
558 getQNameFromSourceIdentifiers(resolutionException.getUnsatisfiedImports().keySet()),
559 UnavailableCapability.FailureReason.UnableToResolve);
560 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
561 id, resolutionException.getUnsatisfiedImports());
562 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
563 id, resolutionException.getUnsatisfiedImports(), resolutionException);
564 return resolutionException.getResolvedSources();
567 private List<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
568 final var tmp = new ArrayList<>(requiredSources);
569 checkState(tmp.remove(sourceIdToRemove), "%s: Trying to remove %s from %s failed", id, sourceIdToRemove,
574 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
575 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
577 if (qNames.isEmpty()) {
578 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
581 return Collections2.filter(qNames, Predicates.notNull());
584 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
585 // Required sources are all required and provided merged in DeviceSourcesResolver
586 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
587 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
591 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
595 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
596 deviceSources.getRequiredSourcesQName());
597 // return null since we cannot find the QName,
598 // this capability will be removed from required sources and not reported as unresolved-capability