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.Sets;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.ListeningExecutorService;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import com.google.common.util.concurrent.SettableFuture;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.Objects;
30 import java.util.concurrent.ExecutionException;
31 import java.util.stream.Collectors;
32 import org.checkerframework.checker.lock.qual.GuardedBy;
33 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
34 import org.opendaylight.mdsal.dom.api.DOMRpcService;
35 import org.opendaylight.netconf.api.NetconfMessage;
36 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
37 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
38 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
39 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
40 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
41 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
42 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
43 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
44 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
45 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
46 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
47 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseNetconfSchemas;
48 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
49 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
50 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
51 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
55 import org.opendaylight.yangtools.concepts.Registration;
56 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
57 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
58 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
59 import org.opendaylight.yangtools.yang.common.QName;
60 import org.opendaylight.yangtools.yang.common.RpcError;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
65 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
66 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
67 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
68 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
69 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
70 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
71 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
72 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
73 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
78 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
80 public class NetconfDevice implements RemoteDevice<NetconfDeviceCommunicator> {
81 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
83 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
84 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
85 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
86 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
88 protected final RemoteDeviceId id;
89 protected final EffectiveModelContextFactory schemaContextFactory;
90 protected final SchemaSourceRegistry schemaRegistry;
91 protected final SchemaRepository schemaRepository;
93 protected final List<Registration> sourceRegistrations = new ArrayList<>();
95 private final RemoteDeviceHandler salFacade;
96 private final ListeningExecutorService processingExecutor;
97 private final DeviceActionFactory deviceActionFactory;
98 private final NetconfDeviceSchemasResolver stateSchemasResolver;
99 private final NotificationHandler notificationHandler;
100 private final boolean reconnectOnSchemasChange;
101 private final BaseNetconfSchemas baseSchemas;
104 private boolean connected = false;
106 // Message transformer is constructed once the schemas are available
107 private MessageTransformer messageTransformer;
109 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
110 final RemoteDeviceId id, final RemoteDeviceHandler salFacade,
111 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
112 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
115 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
116 final RemoteDeviceId id, final RemoteDeviceHandler salFacade,
117 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
118 final DeviceActionFactory deviceActionFactory) {
119 this.baseSchemas = requireNonNull(baseSchemas);
121 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
122 this.deviceActionFactory = deviceActionFactory;
123 schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
124 schemaRepository = schemaResourcesDTO.getSchemaRepository();
125 schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
126 this.salFacade = salFacade;
127 stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
128 processingExecutor = requireNonNull(globalProcessingExecutor);
129 notificationHandler = new NotificationHandler(salFacade, id);
133 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
134 final NetconfDeviceCommunicator listener) {
135 // SchemaContext setup has to be performed in a dedicated thread since
136 // we are in a netty thread in this method
137 // Yang models are being downloaded in this method and it would cause a
138 // deadlock if we used the netty thread
139 // http://netty.io/wiki/thread-model.html
141 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
143 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
144 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
145 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
146 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
147 new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
149 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
150 registerToBaseNetconfStream(initRpc, listener);
153 // Set up the SchemaContext for the device
154 final ListenableFuture<EffectiveModelContext> futureSchema = Futures.transformAsync(sourceResolverFuture,
155 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
157 // Potentially acquire mount point list and interpret it
158 final ListenableFuture<MountPointContext> futureContext = Futures.transformAsync(futureSchema,
159 schemaContext -> createMountPointContext(schemaContext, baseSchema, listener), processingExecutor);
161 Futures.addCallback(futureContext, new FutureCallback<MountPointContext>() {
163 public void onSuccess(final MountPointContext result) {
164 handleSalInitializationSuccess(result, remoteSessionCapabilities,
165 getDeviceSpecificRpc(result, listener, baseSchema), listener);
169 public void onFailure(final Throwable cause) {
170 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
171 // FIXME: this causes salFacade to see onDeviceDisconnected() and then onDeviceFailed(), which is quite
173 handleSalInitializationFailure(cause, listener);
174 salFacade.onDeviceFailed(cause);
176 }, MoreExecutors.directExecutor());
179 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
180 final NetconfDeviceCommunicator listener) {
181 // TODO check whether the model describing create subscription is present in schema
182 // Perhaps add a default schema context to support create-subscription if the model was not provided
183 // (same as what we do for base netconf operations in transformer)
184 final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
185 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
186 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
188 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
190 public void onSuccess(final DOMRpcResult domRpcResult) {
191 notificationHandler.addNotificationFilter(notification -> {
192 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getIdentifier().getNodeType())) {
193 LOG.info("{}: Schemas change detected, reconnecting", id);
194 // Only disconnect is enough,
195 // the reconnecting nature of the connector will take care of reconnecting
196 listener.disconnect();
204 public void onFailure(final Throwable throwable) {
205 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
208 }, MoreExecutors.directExecutor());
211 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
212 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
215 private synchronized void handleSalInitializationSuccess(final MountPointContext result,
216 final NetconfSessionPreferences remoteSessionCapabilities, final DOMRpcService deviceRpc,
217 final RemoteDeviceCommunicator listener) {
218 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
219 //since salFacade.onDeviceDisconnected was already called.
221 messageTransformer = new NetconfMessageTransformer(result, true,
222 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
224 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
225 salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
226 deviceActionFactory == null ? null : deviceActionFactory.createDeviceAction(
227 messageTransformer, listener, result.getEffectiveModelContext()));
228 notificationHandler.onRemoteSchemaUp(messageTransformer);
230 LOG.info("{}: Netconf connector initialized successfully", id);
232 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
236 private void handleSalInitializationFailure(final Throwable throwable, final RemoteDeviceCommunicator listener) {
237 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
239 onRemoteSessionDown();
240 resetMessageTransformer();
244 * Set the transformer to null as is in initial state.
246 private void resetMessageTransformer() {
247 updateTransformer(null);
250 private synchronized void updateTransformer(final MessageTransformer transformer) {
251 messageTransformer = transformer;
254 private synchronized void setConnected(final boolean connected) {
255 this.connected = connected;
258 private ListenableFuture<EffectiveModelContext> assembleSchemaContext(final DeviceSources deviceSources,
259 final NetconfSessionPreferences remoteSessionCapabilities) {
260 LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
262 sourceRegistrations.addAll(deviceSources.register(schemaRegistry));
264 return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
267 private ListenableFuture<MountPointContext> createMountPointContext(final EffectiveModelContext schemaContext,
268 final BaseSchema baseSchema, final NetconfDeviceCommunicator listener) {
269 final MountPointContext emptyContext = new EmptyMountPointContext(schemaContext);
270 if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
271 return Futures.immediateFuture(emptyContext);
274 // Create a temporary RPC invoker and acquire the mount point tree
275 LOG.debug("{}: Acquiring available mount points", id);
276 final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
277 new NetconfMessageTransformer(emptyContext, false, baseSchema));
279 return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
280 Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
281 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
282 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
285 private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
286 final Collection<? extends RpcError> errors = rpcResult.getErrors();
287 if (!errors.isEmpty()) {
288 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
290 final NormalizedNode schemaMounts = rpcResult.getResult();
291 if (schemaMounts == null) {
292 LOG.debug("{}: device does not define any schema mounts", id);
295 if (!(schemaMounts instanceof ContainerNode)) {
296 LOG.warn("{}: ignoring non-container schema mounts {}", id, schemaMounts);
300 return DeviceMountPointContext.create(emptyContext, (ContainerNode) schemaMounts);
304 public void onRemoteSessionDown() {
306 notificationHandler.onRemoteSchemaDown();
308 salFacade.onDeviceDisconnected();
309 sourceRegistrations.forEach(Registration::close);
310 sourceRegistrations.clear();
311 resetMessageTransformer();
315 public void onRemoteSessionFailed(final Throwable throwable) {
317 salFacade.onDeviceFailed(throwable);
321 public void onNotification(final NetconfMessage notification) {
322 notificationHandler.handleNotification(notification);
325 private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
326 return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
329 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
330 final RemoteDeviceCommunicator listener, final BaseSchema schema) {
331 return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
332 new NetconfMessageTransformer(result, true, schema));
336 * Just a transfer object containing schema related dependencies. Injected in constructor.
338 public static class SchemaResourcesDTO {
339 private final SchemaSourceRegistry schemaRegistry;
340 private final SchemaRepository schemaRepository;
341 private final EffectiveModelContextFactory schemaContextFactory;
342 private final NetconfDeviceSchemasResolver stateSchemasResolver;
344 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
345 final SchemaRepository schemaRepository,
346 final EffectiveModelContextFactory schemaContextFactory,
347 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
348 this.schemaRegistry = requireNonNull(schemaRegistry);
349 this.schemaRepository = requireNonNull(schemaRepository);
350 this.schemaContextFactory = requireNonNull(schemaContextFactory);
351 stateSchemasResolver = requireNonNull(deviceSchemasResolver);
354 public SchemaSourceRegistry getSchemaRegistry() {
355 return schemaRegistry;
358 public SchemaRepository getSchemaRepository() {
359 return schemaRepository;
362 public EffectiveModelContextFactory getSchemaContextFactory() {
363 return schemaContextFactory;
366 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
367 return stateSchemasResolver;
372 * A dedicated exception to indicate when we fail to setup an {@link EffectiveModelContext}.
374 public static final class EmptySchemaContextException extends Exception {
375 private static final long serialVersionUID = 1L;
377 public EmptySchemaContextException(final String message) {
383 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
385 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
386 private final SettableFuture<EffectiveModelContext> resultFuture = SettableFuture.create();
388 private final DeviceSources deviceSources;
389 private final NetconfSessionPreferences remoteSessionCapabilities;
390 private final NetconfDeviceCapabilities capabilities;
392 private Collection<SourceIdentifier> requiredSources;
394 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
395 this.deviceSources = deviceSources;
396 this.remoteSessionCapabilities = remoteSessionCapabilities;
397 capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
399 // If device supports notifications and does not contain necessary modules, add them automatically
400 if (remoteSessionCapabilities.containsNonModuleCapability(
401 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0)) {
402 deviceSources.getRequiredSourcesQName().addAll(
404 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
405 .$YangModuleInfoImpl.getInstance().getName(),
406 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
407 .$YangModuleInfoImpl.getInstance().getName()
412 requiredSources = deviceSources.getRequiredSources();
413 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
415 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
416 UnavailableCapability.FailureReason.MissingSource);
417 requiredSources.removeAll(missingSources);
420 ListenableFuture<EffectiveModelContext> startResolution() {
426 public void onSuccess(final EffectiveModelContext result) {
427 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
429 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
430 capabilities.getUnresolvedCapabilites().keySet());
431 capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
432 .setCapability(entry.toString()).setCapabilityOrigin(
433 remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
434 .collect(Collectors.toList()));
436 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
437 .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
438 .setCapability(entry).setCapabilityOrigin(
439 remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
440 .collect(Collectors.toList()));
442 resultFuture.set(result);
446 public void onFailure(final Throwable cause) {
447 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
448 // that might be wrapping a MissingSchemaSourceException so we need to look
449 // at the cause of the exception to make sure we don't misinterpret it.
450 if (cause instanceof MissingSchemaSourceException) {
451 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
452 } else if (cause instanceof SchemaResolutionException) {
453 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
455 LOG.debug("Unhandled failure", cause);
456 resultFuture.setException(cause);
464 private void trySetupSchema() {
465 if (!requiredSources.isEmpty()) {
466 // Initiate async resolution, drive it back based on the result
467 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
468 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
469 MoreExecutors.directExecutor());
471 LOG.debug("{}: no more sources for schema context", id);
472 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
476 private List<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
477 return origSources.parallelStream().filter(sourceIdentifier -> {
479 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
481 } catch (InterruptedException | ExecutionException e) {
484 }).collect(Collectors.toList());
487 private List<SourceIdentifier> handleMissingSchemaSourceException(
488 final MissingSchemaSourceException exception) {
489 // In case source missing, try without it
490 final SourceIdentifier missingSource = exception.getSourceId();
491 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
493 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
494 id, missingSource, exception);
495 final Collection<QName> qNameOfMissingSource =
496 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
497 if (!qNameOfMissingSource.isEmpty()) {
498 capabilities.addUnresolvedCapabilities(
499 qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
501 return stripUnavailableSource(missingSource);
504 private Collection<SourceIdentifier> handleSchemaResolutionException(
505 final SchemaResolutionException resolutionException) {
506 // In case resolution error, try only with resolved sources
507 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
508 // FIXME Do we really have assurance that these two cases cannot happen at once?
509 if (resolutionException.getFailedSource() != null) {
510 // flawed model - exclude it
511 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
512 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
514 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
515 id, failedSourceId, resolutionException);
516 capabilities.addUnresolvedCapabilities(
517 getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
518 UnavailableCapability.FailureReason.UnableToResolve);
519 return stripUnavailableSource(resolutionException.getFailedSource());
521 // unsatisfied imports
522 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
523 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
524 UnavailableCapability.FailureReason.UnableToResolve);
525 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
526 id, resolutionException.getUnsatisfiedImports());
527 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
528 id, resolutionException.getUnsatisfiedImports(), resolutionException);
529 return resolutionException.getResolvedSources();
532 private List<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
533 final var tmp = new ArrayList<>(requiredSources);
534 checkState(tmp.remove(sourceIdToRemove), "%s: Trying to remove %s from %s failed", id, sourceIdToRemove,
539 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
540 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
542 if (qNames.isEmpty()) {
543 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
546 return Collections2.filter(qNames, Predicates.notNull());
549 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
550 // Required sources are all required and provided merged in DeviceSourcesResolver
551 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
552 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
556 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
560 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
561 deviceSources.getRequiredSourcesQName());
562 // return null since we cannot find the QName,
563 // this capability will be removed from required sources and not reported as unresolved-capability