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.mdsal.dom.api.DOMRpcService;
40 import org.opendaylight.netconf.api.NetconfMessage;
41 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
42 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
43 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
44 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
45 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
46 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
47 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
50 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
51 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
52 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseNetconfSchemas;
53 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
54 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
55 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
56 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability.FailureReason;
62 import org.opendaylight.yangtools.concepts.Registration;
63 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
64 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
65 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
66 import org.opendaylight.yangtools.yang.common.QName;
67 import org.opendaylight.yangtools.yang.common.RpcError;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
72 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
73 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
74 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
75 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
76 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
77 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
78 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
79 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
80 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
85 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
87 public class NetconfDevice implements RemoteDevice<NetconfDeviceCommunicator> {
88 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
90 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
91 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
92 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
93 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
95 protected final RemoteDeviceId id;
96 protected final EffectiveModelContextFactory schemaContextFactory;
97 protected final SchemaSourceRegistry schemaRegistry;
98 protected final SchemaRepository schemaRepository;
100 protected final List<Registration> sourceRegistrations = new ArrayList<>();
102 private final RemoteDeviceHandler salFacade;
103 private final ListeningExecutorService processingExecutor;
104 private final DeviceActionFactory deviceActionFactory;
105 private final NetconfDeviceSchemasResolver stateSchemasResolver;
106 private final NotificationHandler notificationHandler;
107 private final boolean reconnectOnSchemasChange;
108 private final BaseNetconfSchemas baseSchemas;
111 private boolean connected = false;
113 // Message transformer is constructed once the schemas are available
114 private MessageTransformer messageTransformer;
116 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
117 final RemoteDeviceId id, final RemoteDeviceHandler salFacade,
118 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
119 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
122 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
123 final RemoteDeviceId id, final RemoteDeviceHandler salFacade,
124 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
125 final DeviceActionFactory deviceActionFactory) {
126 this.baseSchemas = requireNonNull(baseSchemas);
128 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
129 this.deviceActionFactory = deviceActionFactory;
130 schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
131 schemaRepository = schemaResourcesDTO.getSchemaRepository();
132 schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
133 this.salFacade = salFacade;
134 stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
135 processingExecutor = requireNonNull(globalProcessingExecutor);
136 notificationHandler = new NotificationHandler(salFacade, id);
140 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
141 final NetconfDeviceCommunicator listener) {
142 // SchemaContext setup has to be performed in a dedicated thread since
143 // we are in a netty thread in this method
144 // Yang models are being downloaded in this method and it would cause a
145 // deadlock if we used the netty thread
146 // http://netty.io/wiki/thread-model.html
148 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
150 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
151 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
152 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
153 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
154 new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
156 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
157 registerToBaseNetconfStream(initRpc, listener);
160 // Set up the SchemaContext for the device
161 final ListenableFuture<SchemaResult> futureSchema = Futures.transformAsync(sourceResolverFuture,
162 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
164 // Potentially acquire mount point list and interpret it
165 final ListenableFuture<NetconfDeviceSchema> futureContext = Futures.transformAsync(futureSchema,
166 result -> Futures.transform(createMountPointContext(result.modelContext(), baseSchema, listener),
167 mount -> new NetconfDeviceSchema(result.capabilities(), mount), processingExecutor),
170 Futures.addCallback(futureContext, new FutureCallback<>() {
172 public void onSuccess(final NetconfDeviceSchema result) {
173 handleSalInitializationSuccess(result, remoteSessionCapabilities,
174 getDeviceSpecificRpc(result.mountContext(), listener, baseSchema), listener);
178 public void onFailure(final Throwable cause) {
179 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
180 // FIXME: this causes salFacade to see onDeviceDisconnected() and then onDeviceFailed(), which is quite
182 handleSalInitializationFailure(cause, listener);
183 salFacade.onDeviceFailed(cause);
185 }, MoreExecutors.directExecutor());
188 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
189 final NetconfDeviceCommunicator listener) {
190 // TODO check whether the model describing create subscription is present in schema
191 // Perhaps add a default schema context to support create-subscription if the model was not provided
192 // (same as what we do for base netconf operations in transformer)
193 final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
194 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
195 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
197 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
199 public void onSuccess(final DOMRpcResult domRpcResult) {
200 notificationHandler.addNotificationFilter(notification -> {
201 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getIdentifier().getNodeType())) {
202 LOG.info("{}: Schemas change detected, reconnecting", id);
203 // Only disconnect is enough,
204 // the reconnecting nature of the connector will take care of reconnecting
205 listener.disconnect();
213 public void onFailure(final Throwable throwable) {
214 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
217 }, MoreExecutors.directExecutor());
220 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
221 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
224 private synchronized void handleSalInitializationSuccess(final NetconfDeviceSchema deviceSchema,
225 final NetconfSessionPreferences remoteSessionCapabilities, final DOMRpcService deviceRpc,
226 final RemoteDeviceCommunicator listener) {
227 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
228 //since salFacade.onDeviceDisconnected was already called.
230 final var mount = deviceSchema.mountContext();
231 messageTransformer = new NetconfMessageTransformer(mount, true,
232 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
234 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
235 salFacade.onDeviceConnected(deviceSchema, remoteSessionCapabilities, deviceRpc,
236 deviceActionFactory == null ? null : deviceActionFactory.createDeviceAction(
237 messageTransformer, listener, mount.getEffectiveModelContext()));
238 notificationHandler.onRemoteSchemaUp(messageTransformer);
240 LOG.info("{}: Netconf connector initialized successfully", id);
242 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
246 private void handleSalInitializationFailure(final Throwable throwable, final RemoteDeviceCommunicator listener) {
247 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
249 onRemoteSessionDown();
250 resetMessageTransformer();
254 * Set the transformer to null as is in initial state.
256 private void resetMessageTransformer() {
257 updateTransformer(null);
260 private synchronized void updateTransformer(final MessageTransformer transformer) {
261 messageTransformer = transformer;
264 private synchronized void setConnected(final boolean connected) {
265 this.connected = connected;
268 private ListenableFuture<SchemaResult> assembleSchemaContext(final DeviceSources deviceSources,
269 final NetconfSessionPreferences remoteSessionCapabilities) {
270 LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
272 sourceRegistrations.addAll(deviceSources.register(schemaRegistry));
274 return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
277 private ListenableFuture<@NonNull MountPointContext> createMountPointContext(
278 final EffectiveModelContext schemaContext, final BaseSchema baseSchema,
279 final NetconfDeviceCommunicator listener) {
280 final MountPointContext emptyContext = new EmptyMountPointContext(schemaContext);
281 if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
282 return Futures.immediateFuture(emptyContext);
285 // Create a temporary RPC invoker and acquire the mount point tree
286 LOG.debug("{}: Acquiring available mount points", id);
287 final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
288 new NetconfMessageTransformer(emptyContext, false, baseSchema));
290 return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
291 Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
292 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
293 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
296 private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
297 final Collection<? extends RpcError> errors = rpcResult.getErrors();
298 if (!errors.isEmpty()) {
299 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
301 final NormalizedNode schemaMounts = rpcResult.getResult();
302 if (schemaMounts == null) {
303 LOG.debug("{}: device does not define any schema mounts", id);
306 if (!(schemaMounts instanceof ContainerNode)) {
307 LOG.warn("{}: ignoring non-container schema mounts {}", id, schemaMounts);
311 return DeviceMountPointContext.create(emptyContext, (ContainerNode) schemaMounts);
315 public void onRemoteSessionDown() {
317 notificationHandler.onRemoteSchemaDown();
319 salFacade.onDeviceDisconnected();
320 sourceRegistrations.forEach(Registration::close);
321 sourceRegistrations.clear();
322 resetMessageTransformer();
326 public void onRemoteSessionFailed(final Throwable throwable) {
328 salFacade.onDeviceFailed(throwable);
332 public void onNotification(final NetconfMessage notification) {
333 notificationHandler.handleNotification(notification);
336 private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
337 return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
340 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
341 final RemoteDeviceCommunicator listener, final BaseSchema schema) {
342 return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
343 new NetconfMessageTransformer(result, true, schema));
347 * Just a transfer object containing schema related dependencies. Injected in constructor.
349 public static class SchemaResourcesDTO {
350 private final SchemaSourceRegistry schemaRegistry;
351 private final SchemaRepository schemaRepository;
352 private final EffectiveModelContextFactory schemaContextFactory;
353 private final NetconfDeviceSchemasResolver stateSchemasResolver;
355 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
356 final SchemaRepository schemaRepository,
357 final EffectiveModelContextFactory schemaContextFactory,
358 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
359 this.schemaRegistry = requireNonNull(schemaRegistry);
360 this.schemaRepository = requireNonNull(schemaRepository);
361 this.schemaContextFactory = requireNonNull(schemaContextFactory);
362 stateSchemasResolver = requireNonNull(deviceSchemasResolver);
365 public SchemaSourceRegistry getSchemaRegistry() {
366 return schemaRegistry;
369 public SchemaRepository getSchemaRepository() {
370 return schemaRepository;
373 public EffectiveModelContextFactory getSchemaContextFactory() {
374 return schemaContextFactory;
377 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
378 return stateSchemasResolver;
383 * A dedicated exception to indicate when we fail to setup an {@link EffectiveModelContext}.
385 public static final class EmptySchemaContextException extends Exception {
386 private static final long serialVersionUID = 1L;
388 public EmptySchemaContextException(final String message) {
394 * {@link NetconfDeviceCapabilities} and {@link EffectiveModelContext}.
396 private record SchemaResult(
397 @NonNull NetconfDeviceCapabilities capabilities,
398 @NonNull EffectiveModelContext modelContext) {
401 requireNonNull(capabilities);
402 requireNonNull(modelContext);
407 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
409 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
410 private final SettableFuture<SchemaResult> resultFuture = SettableFuture.create();
412 private final Set<AvailableCapability> nonModuleBasedCapabilities = new HashSet<>();
413 private final Map<QName, FailureReason> unresolvedCapabilites = new HashMap<>();
414 private final Set<AvailableCapability> resolvedCapabilities = new HashSet<>();
416 private final DeviceSources deviceSources;
417 private final NetconfSessionPreferences remoteSessionCapabilities;
419 private Collection<SourceIdentifier> requiredSources;
421 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
422 this.deviceSources = deviceSources;
423 this.remoteSessionCapabilities = remoteSessionCapabilities;
425 // If device supports notifications and does not contain necessary modules, add them automatically
426 if (remoteSessionCapabilities.containsNonModuleCapability(
427 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0)) {
428 deviceSources.getRequiredSourcesQName().addAll(
430 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
431 .$YangModuleInfoImpl.getInstance().getName(),
432 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
433 .$YangModuleInfoImpl.getInstance().getName()
438 requiredSources = deviceSources.getRequiredSources();
439 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
441 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
442 UnavailableCapability.FailureReason.MissingSource);
443 requiredSources.removeAll(missingSources);
446 ListenableFuture<SchemaResult> startResolution() {
452 public void onSuccess(final EffectiveModelContext result) {
453 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
455 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
456 unresolvedCapabilites.keySet());
457 resolvedCapabilities.addAll(filteredQNames.stream()
458 .map(capability -> new AvailableCapabilityBuilder()
459 .setCapability(capability.toString())
460 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
462 .collect(Collectors.toList()));
464 nonModuleBasedCapabilities.addAll(remoteSessionCapabilities.getNonModuleCaps().stream()
465 .map(capability -> new AvailableCapabilityBuilder()
466 .setCapability(capability)
467 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
469 .collect(Collectors.toList()));
472 resultFuture.set(new SchemaResult(new NetconfDeviceCapabilities(ImmutableMap.copyOf(unresolvedCapabilites),
473 ImmutableSet.copyOf(resolvedCapabilities), ImmutableSet.copyOf(nonModuleBasedCapabilities)), result));
477 public void onFailure(final Throwable cause) {
478 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
479 // that might be wrapping a MissingSchemaSourceException so we need to look
480 // at the cause of the exception to make sure we don't misinterpret it.
481 if (cause instanceof MissingSchemaSourceException) {
482 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
483 } else if (cause instanceof SchemaResolutionException) {
484 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
486 LOG.debug("Unhandled failure", cause);
487 resultFuture.setException(cause);
495 private void trySetupSchema() {
496 if (!requiredSources.isEmpty()) {
497 // Initiate async resolution, drive it back based on the result
498 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
499 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
500 MoreExecutors.directExecutor());
502 LOG.debug("{}: no more sources for schema context", id);
503 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
507 private List<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
508 return origSources.parallelStream().filter(sourceIdentifier -> {
510 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
512 } catch (InterruptedException | ExecutionException e) {
515 }).collect(Collectors.toList());
518 private void addUnresolvedCapabilities(final Collection<QName> capabilities, final FailureReason reason) {
519 for (QName s : capabilities) {
520 unresolvedCapabilites.put(s, reason);
524 private List<SourceIdentifier> handleMissingSchemaSourceException(
525 final MissingSchemaSourceException exception) {
526 // In case source missing, try without it
527 final SourceIdentifier missingSource = exception.getSourceId();
528 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
530 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
531 id, missingSource, exception);
532 final var qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
533 if (!qNameOfMissingSource.isEmpty()) {
534 addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
536 return stripUnavailableSource(missingSource);
539 private Collection<SourceIdentifier> handleSchemaResolutionException(
540 final SchemaResolutionException resolutionException) {
541 // In case resolution error, try only with resolved sources
542 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
543 // FIXME Do we really have assurance that these two cases cannot happen at once?
544 if (resolutionException.getFailedSource() != null) {
545 // flawed model - exclude it
546 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
547 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
549 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
550 id, failedSourceId, resolutionException);
551 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(List.of(failedSourceId)),
552 UnavailableCapability.FailureReason.UnableToResolve);
553 return stripUnavailableSource(resolutionException.getFailedSource());
555 // unsatisfied imports
556 addUnresolvedCapabilities(
557 getQNameFromSourceIdentifiers(resolutionException.getUnsatisfiedImports().keySet()),
558 UnavailableCapability.FailureReason.UnableToResolve);
559 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
560 id, resolutionException.getUnsatisfiedImports());
561 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
562 id, resolutionException.getUnsatisfiedImports(), resolutionException);
563 return resolutionException.getResolvedSources();
566 private List<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
567 final var tmp = new ArrayList<>(requiredSources);
568 checkState(tmp.remove(sourceIdToRemove), "%s: Trying to remove %s from %s failed", id, sourceIdToRemove,
573 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
574 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
576 if (qNames.isEmpty()) {
577 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
580 return Collections2.filter(qNames, Predicates.notNull());
583 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
584 // Required sources are all required and provided merged in DeviceSourcesResolver
585 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
586 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
590 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
594 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
595 deviceSources.getRequiredSourcesQName());
596 // return null since we cannot find the QName,
597 // this capability will be removed from required sources and not reported as unresolved-capability