2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.netconf.client.mdsal;
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
14 import com.google.common.base.Predicates;
15 import com.google.common.collect.Collections2;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.Sets;
19 import com.google.common.util.concurrent.FutureCallback;
20 import com.google.common.util.concurrent.Futures;
21 import com.google.common.util.concurrent.ListenableFuture;
22 import com.google.common.util.concurrent.MoreExecutors;
23 import com.google.common.util.concurrent.SettableFuture;
24 import java.io.Serial;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
31 import java.util.Objects;
33 import java.util.concurrent.CancellationException;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.Executor;
36 import java.util.stream.Collectors;
37 import org.checkerframework.checker.lock.qual.GuardedBy;
38 import org.eclipse.jdt.annotation.NonNull;
39 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
40 import org.opendaylight.netconf.api.CapabilityURN;
41 import org.opendaylight.netconf.api.messages.NetconfMessage;
42 import org.opendaylight.netconf.client.mdsal.api.BaseNetconfSchema;
43 import org.opendaylight.netconf.client.mdsal.api.BaseNetconfSchemaProvider;
44 import org.opendaylight.netconf.client.mdsal.api.DeviceActionFactory;
45 import org.opendaylight.netconf.client.mdsal.api.NetconfDeviceSchemasResolver;
46 import org.opendaylight.netconf.client.mdsal.api.NetconfSessionPreferences;
47 import org.opendaylight.netconf.client.mdsal.api.RemoteDevice;
48 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceCommunicator;
49 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceHandler;
50 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
51 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices;
52 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceServices.Rpcs;
53 import org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformUtil;
54 import org.opendaylight.netconf.client.mdsal.impl.NetconfMessageTransformer;
55 import org.opendaylight.netconf.client.mdsal.spi.NetconfDeviceRpc;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.Get;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscription;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
59 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240120.connection.oper.available.capabilities.AvailableCapability;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240120.connection.oper.available.capabilities.AvailableCapabilityBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240120.connection.oper.unavailable.capabilities.UnavailableCapability;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240120.connection.oper.unavailable.capabilities.UnavailableCapability.FailureReason;
64 import org.opendaylight.yangtools.concepts.Registration;
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.api.schema.MountPointContext;
70 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
71 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
72 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
73 import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
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.spi.SchemaSourceRegistry;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
83 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
85 public class NetconfDevice implements RemoteDevice<NetconfDeviceCommunicator> {
86 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
88 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
89 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
90 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.of(
91 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
93 protected final RemoteDeviceId id;
94 protected final EffectiveModelContextFactory schemaContextFactory;
95 protected final SchemaSourceRegistry schemaRegistry;
96 protected final SchemaRepository schemaRepository;
98 protected final List<Registration> sourceRegistrations = new ArrayList<>();
100 private final RemoteDeviceHandler salFacade;
101 private final Executor processingExecutor;
102 private final DeviceActionFactory deviceActionFactory;
103 private final NetconfDeviceSchemasResolver stateSchemasResolver;
104 private final NotificationHandler notificationHandler;
105 private final boolean reconnectOnSchemasChange;
106 private final BaseNetconfSchemaProvider baseSchemas;
109 private ListenableFuture<List<Object>> schemaFuturesList;
111 private boolean connected = false;
113 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemaProvider baseSchemas,
114 final RemoteDeviceId id, final RemoteDeviceHandler salFacade, final Executor globalProcessingExecutor,
115 final boolean reconnectOnSchemasChange) {
116 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
119 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemaProvider baseSchemas,
120 final RemoteDeviceId id, final RemoteDeviceHandler salFacade, final Executor globalProcessingExecutor,
121 final boolean reconnectOnSchemasChange, final DeviceActionFactory deviceActionFactory) {
122 this.baseSchemas = requireNonNull(baseSchemas);
124 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
125 this.deviceActionFactory = deviceActionFactory;
126 schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
127 schemaRepository = schemaResourcesDTO.getSchemaRepository();
128 schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
129 this.salFacade = salFacade;
130 stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
131 processingExecutor = requireNonNull(globalProcessingExecutor);
132 notificationHandler = new NotificationHandler(salFacade, id);
136 public synchronized void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
137 final NetconfDeviceCommunicator listener) {
138 // SchemaContext setup has to be performed in a dedicated thread since we are in a Netty thread in this method
139 // YANG models are being downloaded in this method and it would cause a deadlock if we used the netty thread
140 // https://netty.io/wiki/thread-model.html
142 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
144 final var baseSchema = baseSchemas.baseSchemaForCapabilities(remoteSessionCapabilities);
145 final var initRpc = new NetconfDeviceRpc(baseSchema.modelContext(), listener,
146 new NetconfMessageTransformer(baseSchema.mountPointContext(), false, baseSchema));
149 final var futureSchemas = stateSchemasResolver.resolve(initRpc, remoteSessionCapabilities, id,
150 baseSchema.modelContext());
152 // Convert to sources
153 final var sourceResolverFuture = Futures.transform(futureSchemas, availableSchemas -> {
154 final var providedSources = availableSchemas.getAvailableYangSchemasQNames();
155 LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id, providedSources);
157 final var requiredSources = new HashSet<>(remoteSessionCapabilities.moduleBasedCaps().keySet());
158 final var requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
159 if (!requiredSourcesNotProvided.isEmpty()) {
160 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities,"
161 + " required but not provided: {}", id, requiredSourcesNotProvided);
162 LOG.warn("{}: Attempting to build schema context from required sources", id);
165 // Here all the sources reported in netconf monitoring are merged with those reported in hello.
166 // It is necessary to perform this since submodules are not mentioned in hello but still required.
167 // This clashes with the option of a user to specify supported yang models manually in configuration
168 // for netconf-connector and as a result one is not able to fully override yang models of a device.
169 // It is only possible to add additional models.
170 final var providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
171 if (!providedSourcesNotRequired.isEmpty()) {
172 LOG.warn("{}: Netconf device provides additional yang models not reported in "
173 + "hello message capabilities: {}", id, providedSourcesNotRequired);
174 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
175 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
176 requiredSources.addAll(providedSourcesNotRequired);
179 final var sourceProvider = availableSchemas instanceof LibraryModulesSchemas libraryModule
180 ? new LibrarySchemaSourceProvider(id, libraryModule.getAvailableModels())
181 : new MonitoringSchemaSourceProvider(id, initRpc.domRpcService());
182 return new DeviceSources(requiredSources, providedSources, sourceProvider);
183 }, MoreExecutors.directExecutor());
185 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
186 registerToBaseNetconfStream(initRpc, listener);
189 // Set up the EffectiveModelContext for the device
190 final var futureSchema = Futures.transformAsync(sourceResolverFuture,
191 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
193 // Potentially acquire mount point list and interpret it
194 final var netconfDeviceSchemaFuture = Futures.transformAsync(futureSchema,
195 result -> Futures.transform(createMountPointContext(result.modelContext(), baseSchema, listener),
196 mount -> new NetconfDeviceSchema(result.capabilities(), mount), processingExecutor),
198 schemaFuturesList = Futures.allAsList(sourceResolverFuture, futureSchema, netconfDeviceSchemaFuture);
200 Futures.addCallback(netconfDeviceSchemaFuture, new FutureCallback<>() {
202 public void onSuccess(final NetconfDeviceSchema result) {
203 handleSalInitializationSuccess(listener, baseSchema, result, remoteSessionCapabilities,
204 getDeviceSpecificRpc(result.mountContext(), listener, baseSchema));
208 public void onFailure(final Throwable cause) {
209 // The method onRemoteSessionDown was called while the EffectiveModelContext for the device
210 // was being processed.
211 if (cause instanceof CancellationException) {
212 LOG.warn("{}: Device communicator was tear down since the schema setup started", id);
214 handleSalInitializationFailure(listener, cause);
217 }, MoreExecutors.directExecutor());
220 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
221 final NetconfDeviceCommunicator listener) {
222 // TODO check whether the model describing create subscription is present in schema
223 // Perhaps add a default schema context to support create-subscription if the model was not provided
224 // (same as what we do for base netconf operations in transformer)
225 final var rpcResultListenableFuture = deviceRpc.domRpcService()
226 .invokeRpc(CreateSubscription.QNAME, ImmutableNodes.newContainerBuilder()
227 .withNodeIdentifier(NodeIdentifier.create(CreateSubscriptionInput.QNAME))
228 // Note: default 'stream' is 'NETCONF', we do not need to create an explicit leaf
231 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
233 public void onSuccess(final DOMRpcResult domRpcResult) {
234 notificationHandler.addNotificationFilter(notification -> {
235 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().name().getNodeType())) {
236 LOG.info("{}: Schemas change detected, reconnecting", id);
237 // Only disconnect is enough,
238 // the reconnecting nature of the connector will take care of reconnecting
239 listener.disconnect();
247 public void onFailure(final Throwable throwable) {
248 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
251 }, MoreExecutors.directExecutor());
254 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
255 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
258 private synchronized void handleSalInitializationSuccess(final RemoteDeviceCommunicator listener,
259 final BaseNetconfSchema baseSchema, final NetconfDeviceSchema deviceSchema,
260 final NetconfSessionPreferences remoteSessionCapabilities, final Rpcs deviceRpc) {
261 // NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
262 // since salFacade.onDeviceDisconnected was already called.
264 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
268 final var messageTransformer = new NetconfMessageTransformer(deviceSchema.mountContext(), true, baseSchema);
270 // Order is important here: salFacade has to see the device come up and then the notificationHandler can deliver
271 // whatever notifications have been held back
272 salFacade.onDeviceConnected(deviceSchema, remoteSessionCapabilities,
273 new RemoteDeviceServices(deviceRpc, deviceActionFactory == null ? null
274 : deviceActionFactory.createDeviceAction(messageTransformer, listener)));
275 notificationHandler.onRemoteSchemaUp(messageTransformer);
277 LOG.info("{}: Netconf connector initialized successfully", id);
280 private void handleSalInitializationFailure(final RemoteDeviceCommunicator listener, final Throwable cause) {
281 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
283 cleanupInitialization();
284 salFacade.onDeviceFailed(cause);
287 private synchronized void cleanupInitialization() {
289 if (schemaFuturesList != null && !schemaFuturesList.isDone()) {
290 if (!schemaFuturesList.cancel(true)) {
291 LOG.warn("The cleanup of Schema Futures for device {} was unsuccessful.", id);
294 notificationHandler.onRemoteSchemaDown();
295 sourceRegistrations.forEach(Registration::close);
296 sourceRegistrations.clear();
299 private synchronized void setConnected(final boolean connected) {
300 this.connected = connected;
303 private ListenableFuture<SchemaResult> assembleSchemaContext(final DeviceSources deviceSources,
304 final NetconfSessionPreferences remoteSessionCapabilities) {
305 LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
307 sourceRegistrations.addAll(deviceSources.register(schemaRegistry));
309 return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
312 private ListenableFuture<@NonNull MountPointContext> createMountPointContext(
313 final EffectiveModelContext schemaContext, final BaseNetconfSchema baseSchema,
314 final NetconfDeviceCommunicator listener) {
315 final MountPointContext emptyContext = MountPointContext.of(schemaContext);
316 if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
317 return Futures.immediateFuture(emptyContext);
320 // Create a temporary RPC invoker and acquire the mount point tree
321 LOG.debug("{}: Acquiring available mount points", id);
322 final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
323 new NetconfMessageTransformer(emptyContext, false, baseSchema));
325 return Futures.transform(deviceRpc.domRpcService().invokeRpc(Get.QNAME, ImmutableNodes.newContainerBuilder()
326 .withNodeIdentifier(NETCONF_GET_NODEID)
327 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
328 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
331 private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
332 final var errors = rpcResult.errors();
333 if (!errors.isEmpty()) {
334 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
336 final var schemaMounts = rpcResult.value();
337 if (schemaMounts == null) {
338 LOG.debug("{}: device does not define any schema mounts", id);
342 return DeviceMountPointContext.create(emptyContext, schemaMounts);
346 public void onRemoteSessionDown() {
347 cleanupInitialization();
348 salFacade.onDeviceDisconnected();
352 public void onNotification(final NetconfMessage notification) {
353 notificationHandler.handleNotification(notification);
356 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
357 final RemoteDeviceCommunicator listener, final BaseNetconfSchema schema) {
358 return new NetconfDeviceRpc(result.modelContext(), listener,
359 new NetconfMessageTransformer(result, true, schema));
363 * Just a transfer object containing schema related dependencies. Injected in constructor.
365 public static class SchemaResourcesDTO {
366 private final SchemaSourceRegistry schemaRegistry;
367 private final SchemaRepository schemaRepository;
368 private final EffectiveModelContextFactory schemaContextFactory;
369 private final NetconfDeviceSchemasResolver stateSchemasResolver;
371 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
372 final SchemaRepository schemaRepository,
373 final EffectiveModelContextFactory schemaContextFactory,
374 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
375 this.schemaRegistry = requireNonNull(schemaRegistry);
376 this.schemaRepository = requireNonNull(schemaRepository);
377 this.schemaContextFactory = requireNonNull(schemaContextFactory);
378 stateSchemasResolver = requireNonNull(deviceSchemasResolver);
381 public SchemaSourceRegistry getSchemaRegistry() {
382 return schemaRegistry;
385 public SchemaRepository getSchemaRepository() {
386 return schemaRepository;
389 public EffectiveModelContextFactory getSchemaContextFactory() {
390 return schemaContextFactory;
393 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
394 return stateSchemasResolver;
399 * A dedicated exception to indicate when we fail to setup an {@link EffectiveModelContext}.
401 public static final class EmptySchemaContextException extends Exception {
403 private static final long serialVersionUID = 1L;
405 public EmptySchemaContextException(final String message) {
411 * {@link NetconfDeviceCapabilities} and {@link EffectiveModelContext}.
413 private record SchemaResult(
414 @NonNull NetconfDeviceCapabilities capabilities,
415 @NonNull EffectiveModelContext modelContext) {
418 requireNonNull(capabilities);
419 requireNonNull(modelContext);
424 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
426 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
427 private final SettableFuture<SchemaResult> resultFuture = SettableFuture.create();
429 private final Set<AvailableCapability> nonModuleBasedCapabilities = new HashSet<>();
430 private final Map<QName, FailureReason> unresolvedCapabilites = new HashMap<>();
431 private final Set<AvailableCapability> resolvedCapabilities = new HashSet<>();
433 private final DeviceSources deviceSources;
434 private final NetconfSessionPreferences remoteSessionCapabilities;
436 private Collection<SourceIdentifier> requiredSources;
438 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
439 this.deviceSources = deviceSources;
440 this.remoteSessionCapabilities = remoteSessionCapabilities;
442 // If device supports notifications and does not contain necessary modules, add them automatically
443 if (remoteSessionCapabilities.containsNonModuleCapability(CapabilityURN.NOTIFICATION)) {
444 // FIXME: mutable collection modification!
445 deviceSources.getRequiredSourcesQName().addAll(List.of(
446 org.opendaylight.yang.svc.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
447 .YangModuleInfoImpl.getInstance().getName(),
448 org.opendaylight.yang.svc.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
449 .YangModuleInfoImpl.getInstance().getName())
453 requiredSources = deviceSources.getRequiredSources();
454 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
456 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
457 UnavailableCapability.FailureReason.MissingSource);
458 requiredSources.removeAll(missingSources);
461 ListenableFuture<SchemaResult> startResolution() {
467 public void onSuccess(final EffectiveModelContext result) {
468 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
470 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
471 unresolvedCapabilites.keySet());
472 resolvedCapabilities.addAll(filteredQNames.stream()
473 .map(capability -> new AvailableCapabilityBuilder()
474 .setCapability(capability.toString())
475 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
477 .collect(Collectors.toList()));
479 nonModuleBasedCapabilities.addAll(remoteSessionCapabilities.nonModuleCaps().keySet().stream()
480 .map(capability -> new AvailableCapabilityBuilder()
481 .setCapability(capability)
482 .setCapabilityOrigin(remoteSessionCapabilities.capabilityOrigin(capability))
484 .collect(Collectors.toList()));
487 resultFuture.set(new SchemaResult(new NetconfDeviceCapabilities(ImmutableMap.copyOf(unresolvedCapabilites),
488 ImmutableSet.copyOf(resolvedCapabilities), ImmutableSet.copyOf(nonModuleBasedCapabilities)), result));
492 public void onFailure(final Throwable cause) {
493 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
494 // that might be wrapping a MissingSchemaSourceException so we need to look
495 // at the cause of the exception to make sure we don't misinterpret it.
496 if (cause instanceof MissingSchemaSourceException) {
497 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
498 } else if (cause instanceof SchemaResolutionException) {
499 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
501 LOG.debug("Unhandled failure", cause);
502 resultFuture.setException(cause);
510 private void trySetupSchema() {
511 if (!requiredSources.isEmpty()) {
512 // Initiate async resolution, drive it back based on the result
513 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
514 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
515 MoreExecutors.directExecutor());
517 LOG.debug("{}: no more sources for schema context", id);
518 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
522 private List<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
523 return origSources.parallelStream().filter(sourceIdentifier -> {
525 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSource.class).get();
527 } catch (InterruptedException | ExecutionException e) {
530 }).collect(Collectors.toList());
533 private void addUnresolvedCapabilities(final Collection<QName> capabilities, final FailureReason reason) {
534 for (QName s : capabilities) {
535 unresolvedCapabilites.put(s, reason);
539 private List<SourceIdentifier> handleMissingSchemaSourceException(
540 final MissingSchemaSourceException exception) {
541 // In case source missing, try without it
542 final SourceIdentifier missingSource = exception.sourceId();
543 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
545 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
546 id, missingSource, exception);
547 final var qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
548 if (!qNameOfMissingSource.isEmpty()) {
549 addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
551 return stripUnavailableSource(missingSource);
554 private Collection<SourceIdentifier> handleSchemaResolutionException(
555 final SchemaResolutionException resolutionException) {
556 // In case resolution error, try only with resolved sources
557 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
558 // FIXME Do we really have assurance that these two cases cannot happen at once?
559 final var failedSourceId = resolutionException.sourceId();
560 if (failedSourceId != null) {
561 // flawed model - exclude it
562 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
564 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
565 id, failedSourceId, resolutionException);
566 addUnresolvedCapabilities(getQNameFromSourceIdentifiers(List.of(failedSourceId)),
567 UnavailableCapability.FailureReason.UnableToResolve);
568 return stripUnavailableSource(failedSourceId);
570 // unsatisfied imports
571 addUnresolvedCapabilities(
572 getQNameFromSourceIdentifiers(resolutionException.getUnsatisfiedImports().keySet()),
573 UnavailableCapability.FailureReason.UnableToResolve);
574 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
575 id, resolutionException.getUnsatisfiedImports());
576 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
577 id, resolutionException.getUnsatisfiedImports(), resolutionException);
578 return resolutionException.getResolvedSources();
581 private List<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
582 final var tmp = new ArrayList<>(requiredSources);
583 checkState(tmp.remove(sourceIdToRemove), "%s: Trying to remove %s from %s failed", id, sourceIdToRemove,
588 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
589 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
591 if (qNames.isEmpty()) {
592 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
595 return Collections2.filter(qNames, Predicates.notNull());
598 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
599 // Required sources are all required and provided merged in DeviceSourcesResolver
600 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
601 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
605 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
609 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
610 deviceSources.getRequiredSourcesQName());
611 // return null since we cannot find the QName,
612 // this capability will be removed from required sources and not reported as unresolved-capability