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.NetconfDeviceSchemasResolver;
43 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
44 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
45 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
46 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceId;
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.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.oper.available.capabilities.AvailableCapability;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.oper.available.capabilities.AvailableCapabilityBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.oper.unavailable.capabilities.UnavailableCapability;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev230430.connection.oper.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.data.api.YangInstanceIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
69 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
70 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
71 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
72 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
73 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
74 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
75 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
76 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
77 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
82 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
84 public class NetconfDevice implements RemoteDevice<NetconfDeviceCommunicator> {
85 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
87 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
88 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
89 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
90 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
92 protected final RemoteDeviceId id;
93 protected final EffectiveModelContextFactory schemaContextFactory;
94 protected final SchemaSourceRegistry schemaRegistry;
95 protected final SchemaRepository schemaRepository;
97 protected final List<Registration> sourceRegistrations = new ArrayList<>();
99 private final RemoteDeviceHandler salFacade;
100 private final ListeningExecutorService processingExecutor;
101 private final DeviceActionFactory deviceActionFactory;
102 private final NetconfDeviceSchemasResolver stateSchemasResolver;
103 private final NotificationHandler notificationHandler;
104 private final boolean reconnectOnSchemasChange;
105 private final BaseNetconfSchemas baseSchemas;
108 private boolean connected = false;
110 // Message transformer is constructed once the schemas are available
111 private NetconfMessageTransformer messageTransformer;
113 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
114 final RemoteDeviceId id, final RemoteDeviceHandler salFacade,
115 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
116 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
119 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
120 final RemoteDeviceId id, final RemoteDeviceHandler salFacade,
121 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
122 final DeviceActionFactory deviceActionFactory) {
123 this.baseSchemas = requireNonNull(baseSchemas);
125 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
126 this.deviceActionFactory = deviceActionFactory;
127 schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
128 schemaRepository = schemaResourcesDTO.getSchemaRepository();
129 schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
130 this.salFacade = salFacade;
131 stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
132 processingExecutor = requireNonNull(globalProcessingExecutor);
133 notificationHandler = new NotificationHandler(salFacade, id);
137 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
138 final NetconfDeviceCommunicator listener) {
139 // SchemaContext setup has to be performed in a dedicated thread since
140 // we are in a netty thread in this method
141 // Yang models are being downloaded in this method and it would cause a
142 // deadlock if we used the netty thread
143 // http://netty.io/wiki/thread-model.html
145 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
147 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
148 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
149 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
150 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
151 new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
153 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
154 registerToBaseNetconfStream(initRpc, listener);
157 // Set up the SchemaContext for the device
158 final ListenableFuture<SchemaResult> futureSchema = Futures.transformAsync(sourceResolverFuture,
159 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
161 // Potentially acquire mount point list and interpret it
162 final ListenableFuture<NetconfDeviceSchema> futureContext = Futures.transformAsync(futureSchema,
163 result -> Futures.transform(createMountPointContext(result.modelContext(), baseSchema, listener),
164 mount -> new NetconfDeviceSchema(result.capabilities(), mount), processingExecutor),
167 Futures.addCallback(futureContext, new FutureCallback<>() {
169 public void onSuccess(final NetconfDeviceSchema result) {
170 handleSalInitializationSuccess(result, remoteSessionCapabilities,
171 getDeviceSpecificRpc(result.mountContext(), listener, baseSchema), listener);
175 public void onFailure(final Throwable cause) {
176 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
177 // FIXME: this causes salFacade to see onDeviceDisconnected() and then onDeviceFailed(), which is quite
179 handleSalInitializationFailure(cause, listener);
180 salFacade.onDeviceFailed(cause);
182 }, MoreExecutors.directExecutor());
185 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
186 final NetconfDeviceCommunicator listener) {
187 // TODO check whether the model describing create subscription is present in schema
188 // Perhaps add a default schema context to support create-subscription if the model was not provided
189 // (same as what we do for base netconf operations in transformer)
190 final var rpcResultListenableFuture = deviceRpc.invokeRpc(
191 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
192 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
194 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
196 public void onSuccess(final DOMRpcResult domRpcResult) {
197 notificationHandler.addNotificationFilter(notification -> {
198 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getIdentifier().getNodeType())) {
199 LOG.info("{}: Schemas change detected, reconnecting", id);
200 // Only disconnect is enough,
201 // the reconnecting nature of the connector will take care of reconnecting
202 listener.disconnect();
210 public void onFailure(final Throwable throwable) {
211 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
214 }, MoreExecutors.directExecutor());
217 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
218 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
221 private synchronized void handleSalInitializationSuccess(final NetconfDeviceSchema deviceSchema,
222 final NetconfSessionPreferences remoteSessionCapabilities, final Rpcs deviceRpc,
223 final RemoteDeviceCommunicator listener) {
224 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
225 //since salFacade.onDeviceDisconnected was already called.
227 final var mount = deviceSchema.mountContext();
228 messageTransformer = new NetconfMessageTransformer(mount, true,
229 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
231 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
232 salFacade.onDeviceConnected(deviceSchema, remoteSessionCapabilities,
233 new RemoteDeviceServices(deviceRpc, deviceActionFactory == null ? null
234 : deviceActionFactory.createDeviceAction(messageTransformer, listener)));
235 notificationHandler.onRemoteSchemaUp(messageTransformer);
237 LOG.info("{}: Netconf connector initialized successfully", id);
239 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
243 private void handleSalInitializationFailure(final Throwable throwable, final RemoteDeviceCommunicator listener) {
244 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
246 onRemoteSessionDown();
247 resetMessageTransformer();
251 * Set the transformer to null as is in initial state.
253 private void resetMessageTransformer() {
254 updateTransformer(null);
257 private synchronized void updateTransformer(final NetconfMessageTransformer transformer) {
258 messageTransformer = transformer;
261 private synchronized void setConnected(final boolean connected) {
262 this.connected = connected;
265 private ListenableFuture<SchemaResult> assembleSchemaContext(final DeviceSources deviceSources,
266 final NetconfSessionPreferences remoteSessionCapabilities) {
267 LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
269 sourceRegistrations.addAll(deviceSources.register(schemaRegistry));
271 return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
274 private ListenableFuture<@NonNull MountPointContext> createMountPointContext(
275 final EffectiveModelContext schemaContext, final BaseSchema baseSchema,
276 final NetconfDeviceCommunicator listener) {
277 final MountPointContext emptyContext = new EmptyMountPointContext(schemaContext);
278 if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
279 return Futures.immediateFuture(emptyContext);
282 // Create a temporary RPC invoker and acquire the mount point tree
283 LOG.debug("{}: Acquiring available mount points", id);
284 final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
285 new NetconfMessageTransformer(emptyContext, false, baseSchema));
287 return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
288 Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
289 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
290 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
293 private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
294 final var errors = rpcResult.errors();
295 if (!errors.isEmpty()) {
296 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
298 final var schemaMounts = rpcResult.value();
299 if (schemaMounts == null) {
300 LOG.debug("{}: device does not define any schema mounts", id);
304 return DeviceMountPointContext.create(emptyContext, schemaMounts);
308 public void onRemoteSessionDown() {
310 notificationHandler.onRemoteSchemaDown();
312 salFacade.onDeviceDisconnected();
313 sourceRegistrations.forEach(Registration::close);
314 sourceRegistrations.clear();
315 resetMessageTransformer();
319 public void onRemoteSessionFailed(final Throwable throwable) {
321 salFacade.onDeviceFailed(throwable);
325 public void onNotification(final NetconfMessage notification) {
326 notificationHandler.handleNotification(notification);
329 private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
330 return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
333 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
334 final RemoteDeviceCommunicator listener, final BaseSchema schema) {
335 return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
336 new NetconfMessageTransformer(result, true, schema));
340 * Just a transfer object containing schema related dependencies. Injected in constructor.
342 public static class SchemaResourcesDTO {
343 private final SchemaSourceRegistry schemaRegistry;
344 private final SchemaRepository schemaRepository;
345 private final EffectiveModelContextFactory schemaContextFactory;
346 private final NetconfDeviceSchemasResolver stateSchemasResolver;
348 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
349 final SchemaRepository schemaRepository,
350 final EffectiveModelContextFactory schemaContextFactory,
351 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
352 this.schemaRegistry = requireNonNull(schemaRegistry);
353 this.schemaRepository = requireNonNull(schemaRepository);
354 this.schemaContextFactory = requireNonNull(schemaContextFactory);
355 stateSchemasResolver = requireNonNull(deviceSchemasResolver);
358 public SchemaSourceRegistry getSchemaRegistry() {
359 return schemaRegistry;
362 public SchemaRepository getSchemaRepository() {
363 return schemaRepository;
366 public EffectiveModelContextFactory getSchemaContextFactory() {
367 return schemaContextFactory;
370 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
371 return stateSchemasResolver;
376 * A dedicated exception to indicate when we fail to setup an {@link EffectiveModelContext}.
378 public static final class EmptySchemaContextException extends Exception {
379 private static final long serialVersionUID = 1L;
381 public EmptySchemaContextException(final String message) {
387 * {@link NetconfDeviceCapabilities} and {@link EffectiveModelContext}.
389 private record SchemaResult(
390 @NonNull NetconfDeviceCapabilities capabilities,
391 @NonNull EffectiveModelContext modelContext) {
394 requireNonNull(capabilities);
395 requireNonNull(modelContext);
400 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
402 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
403 private final SettableFuture<SchemaResult> resultFuture = SettableFuture.create();
405 private final Set<AvailableCapability> nonModuleBasedCapabilities = new HashSet<>();
406 private final Map<QName, FailureReason> unresolvedCapabilites = new HashMap<>();
407 private final Set<AvailableCapability> resolvedCapabilities = new HashSet<>();
409 private final DeviceSources deviceSources;
410 private final NetconfSessionPreferences remoteSessionCapabilities;
412 private Collection<SourceIdentifier> requiredSources;
414 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
415 this.deviceSources = deviceSources;
416 this.remoteSessionCapabilities = remoteSessionCapabilities;
418 // If device supports notifications and does not contain necessary modules, add them automatically
419 if (remoteSessionCapabilities.containsNonModuleCapability(
420 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0)) {
421 deviceSources.getRequiredSourcesQName().addAll(
423 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
424 .$YangModuleInfoImpl.getInstance().getName(),
425 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
426 .$YangModuleInfoImpl.getInstance().getName()
431 requiredSources = deviceSources.getRequiredSources();
432 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
434 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
435 UnavailableCapability.FailureReason.MissingSource);
436 requiredSources.removeAll(missingSources);
439 ListenableFuture<SchemaResult> startResolution() {
445 public void onSuccess(final EffectiveModelContext result) {
446 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
448 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
449 unresolvedCapabilites.keySet());
450 resolvedCapabilities.addAll(filteredQNames.stream()
451 .map(capability -> new AvailableCapabilityBuilder()
452 .setCapability(capability.toString())
453 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
455 .collect(Collectors.toList()));
457 nonModuleBasedCapabilities.addAll(remoteSessionCapabilities.nonModuleCaps().keySet().stream()
458 .map(capability -> new AvailableCapabilityBuilder()
459 .setCapability(capability)
460 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
462 .collect(Collectors.toList()));
465 resultFuture.set(new SchemaResult(new NetconfDeviceCapabilities(ImmutableMap.copyOf(unresolvedCapabilites),
466 ImmutableSet.copyOf(resolvedCapabilities), ImmutableSet.copyOf(nonModuleBasedCapabilities)), result));
470 public void onFailure(final Throwable cause) {
471 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
472 // that might be wrapping a MissingSchemaSourceException so we need to look
473 // at the cause of the exception to make sure we don't misinterpret it.
474 if (cause instanceof MissingSchemaSourceException) {
475 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
476 } else if (cause instanceof SchemaResolutionException) {
477 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
479 LOG.debug("Unhandled failure", cause);
480 resultFuture.setException(cause);
488 private void trySetupSchema() {
489 if (!requiredSources.isEmpty()) {
490 // Initiate async resolution, drive it back based on the result
491 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
492 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
493 MoreExecutors.directExecutor());
495 LOG.debug("{}: no more sources for schema context", id);
496 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
500 private List<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
501 return origSources.parallelStream().filter(sourceIdentifier -> {
503 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
505 } catch (InterruptedException | ExecutionException e) {
508 }).collect(Collectors.toList());
511 private void addUnresolvedCapabilities(final Collection<QName> capabilities, final FailureReason reason) {
512 for (QName s : capabilities) {
513 unresolvedCapabilites.put(s, reason);
517 private List<SourceIdentifier> handleMissingSchemaSourceException(
518 final MissingSchemaSourceException exception) {
519 // In case source missing, try without it
520 final SourceIdentifier missingSource = exception.getSourceId();
521 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
523 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
524 id, missingSource, exception);
525 final var qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
526 if (!qNameOfMissingSource.isEmpty()) {
527 addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
529 return stripUnavailableSource(missingSource);
532 private Collection<SourceIdentifier> handleSchemaResolutionException(
533 final SchemaResolutionException resolutionException) {
534 // In case resolution error, try only with resolved sources
535 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
536 // FIXME Do we really have assurance that these two cases cannot happen at once?
537 if (resolutionException.getFailedSource() != null) {
538 // flawed model - exclude it
539 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
540 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
542 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
543 id, failedSourceId, resolutionException);
544 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(List.of(failedSourceId)),
545 UnavailableCapability.FailureReason.UnableToResolve);
546 return stripUnavailableSource(resolutionException.getFailedSource());
548 // unsatisfied imports
549 addUnresolvedCapabilities(
550 getQNameFromSourceIdentifiers(resolutionException.getUnsatisfiedImports().keySet()),
551 UnavailableCapability.FailureReason.UnableToResolve);
552 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
553 id, resolutionException.getUnsatisfiedImports());
554 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
555 id, resolutionException.getUnsatisfiedImports(), resolutionException);
556 return resolutionException.getResolvedSources();
559 private List<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
560 final var tmp = new ArrayList<>(requiredSources);
561 checkState(tmp.remove(sourceIdToRemove), "%s: Trying to remove %s from %s failed", id, sourceIdToRemove,
566 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
567 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
569 if (qNames.isEmpty()) {
570 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
573 return Collections2.filter(qNames, Predicates.notNull());
576 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
577 // Required sources are all required and provided merged in DeviceSourcesResolver
578 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
579 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
583 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
587 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
588 deviceSources.getRequiredSourcesQName());
589 // return null since we cannot find the QName,
590 // this capability will be removed from required sources and not reported as unresolved-capability