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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24 import io.netty.util.concurrent.EventExecutor;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.LinkedList;
30 import java.util.List;
31 import java.util.Objects;
32 import java.util.Optional;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.TimeUnit;
36 import java.util.stream.Collectors;
37 import org.checkerframework.checker.lock.qual.GuardedBy;
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.optional.rev190614.NetconfNodeAugmentedOptional;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
62 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
63 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
64 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
65 import org.opendaylight.yangtools.yang.common.QName;
66 import org.opendaylight.yangtools.yang.common.RpcError;
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.ContainerNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
71 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
72 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
73 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
74 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
75 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
76 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
77 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
78 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
79 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
80 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
81 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
82 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
87 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
89 public class NetconfDevice
90 implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
92 @SuppressFBWarnings(value = "SLF4J_LOGGER_SHOULD_BE_PRIVATE",
93 justification = "Needed for common logging of related classes")
94 static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
96 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
97 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
98 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
99 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
101 protected final RemoteDeviceId id;
102 protected final EffectiveModelContextFactory schemaContextFactory;
103 protected final SchemaSourceRegistry schemaRegistry;
104 protected final SchemaRepository schemaRepository;
106 protected final List<SchemaSourceRegistration<?>> sourceRegistrations = new ArrayList<>();
108 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
109 private final ListeningExecutorService processingExecutor;
110 private final DeviceActionFactory deviceActionFactory;
111 private final NetconfDeviceSchemasResolver stateSchemasResolver;
112 private final NotificationHandler notificationHandler;
113 private final boolean reconnectOnSchemasChange;
114 private final BaseNetconfSchemas baseSchemas;
115 private final NetconfNode node;
116 private final EventExecutor eventExecutor;
117 private final NetconfNodeAugmentedOptional nodeOptional;
120 private boolean connected = false;
122 // Message transformer is constructed once the schemas are available
123 private MessageTransformer<NetconfMessage> messageTransformer;
125 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
126 final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
127 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
128 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null,
132 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
133 final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
134 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
135 final DeviceActionFactory deviceActionFactory, final NetconfNode node, final EventExecutor eventExecutor,
136 final NetconfNodeAugmentedOptional nodeOptional) {
137 this.baseSchemas = requireNonNull(baseSchemas);
139 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
140 this.deviceActionFactory = deviceActionFactory;
142 this.eventExecutor = eventExecutor;
143 this.nodeOptional = nodeOptional;
144 schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
145 schemaRepository = schemaResourcesDTO.getSchemaRepository();
146 schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
147 this.salFacade = salFacade;
148 stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
149 processingExecutor = requireNonNull(globalProcessingExecutor);
150 notificationHandler = new NotificationHandler(salFacade, id);
154 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
155 final NetconfDeviceCommunicator listener) {
156 // SchemaContext setup has to be performed in a dedicated thread since
157 // we are in a netty thread in this method
158 // Yang models are being downloaded in this method and it would cause a
159 // deadlock if we used the netty thread
160 // http://netty.io/wiki/thread-model.html
162 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
164 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
165 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
166 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
167 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
168 new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
170 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
171 registerToBaseNetconfStream(initRpc, listener);
174 // Set up the SchemaContext for the device
175 final ListenableFuture<EffectiveModelContext> futureSchema = Futures.transformAsync(sourceResolverFuture,
176 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
178 // Potentially acquire mount point list and interpret it
179 final ListenableFuture<MountPointContext> futureContext = Futures.transformAsync(futureSchema,
180 schemaContext -> createMountPointContext(schemaContext, baseSchema, listener), processingExecutor);
182 Futures.addCallback(futureContext, new FutureCallback<MountPointContext>() {
184 public void onSuccess(final MountPointContext result) {
185 handleSalInitializationSuccess(result, remoteSessionCapabilities,
186 getDeviceSpecificRpc(result, listener, baseSchema), listener);
190 public void onFailure(final Throwable cause) {
191 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
193 // No more sources, fail or try to reconnect
194 if (cause instanceof EmptySchemaContextException) {
195 if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().getAllowed()) {
196 eventExecutor.schedule(() -> {
197 LOG.warn("Reconnection is allowed! This can lead to unexpected errors at runtime.");
198 LOG.warn("{} : No more sources for schema context.", id);
199 LOG.info("{} : Try to remount device.", id);
200 onRemoteSessionDown();
201 salFacade.onDeviceReconnected(remoteSessionCapabilities, node);
202 }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime().toJava(),
203 TimeUnit.MILLISECONDS);
208 handleSalInitializationFailure(cause, listener);
209 salFacade.onDeviceFailed(cause);
211 }, MoreExecutors.directExecutor());
214 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
215 final NetconfDeviceCommunicator listener) {
216 // TODO check whether the model describing create subscription is present in schema
217 // Perhaps add a default schema context to support create-subscription if the model was not provided
218 // (same as what we do for base netconf operations in transformer)
219 final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
220 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
221 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
223 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
225 public void onSuccess(final DOMRpcResult domRpcResult) {
226 notificationHandler.addNotificationFilter(notification -> {
227 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getIdentifier().getNodeType())) {
228 LOG.info("{}: Schemas change detected, reconnecting", id);
229 // Only disconnect is enough,
230 // the reconnecting nature of the connector will take care of reconnecting
231 listener.disconnect();
232 return Optional.empty();
234 return Optional.of(notification);
239 public void onFailure(final Throwable throwable) {
240 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
243 }, MoreExecutors.directExecutor());
246 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
247 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
250 private synchronized void handleSalInitializationSuccess(final MountPointContext result,
251 final NetconfSessionPreferences remoteSessionCapabilities,
252 final DOMRpcService deviceRpc,
253 final RemoteDeviceCommunicator<NetconfMessage> listener) {
254 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
255 //since salFacade.onDeviceDisconnected was already called.
257 messageTransformer = new NetconfMessageTransformer(result, true,
258 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
260 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
261 salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
262 deviceActionFactory == null ? null : deviceActionFactory.createDeviceAction(
263 messageTransformer, listener, result.getEffectiveModelContext()));
264 notificationHandler.onRemoteSchemaUp(messageTransformer);
266 LOG.info("{}: Netconf connector initialized successfully", id);
268 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
272 private void handleSalInitializationFailure(final Throwable throwable,
273 final RemoteDeviceCommunicator<NetconfMessage> listener) {
274 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
276 onRemoteSessionDown();
277 resetMessageTransformer();
281 * Set the transformer to null as is in initial state.
283 private void resetMessageTransformer() {
284 updateTransformer(null);
287 private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
288 messageTransformer = transformer;
291 private synchronized void setConnected(final boolean connected) {
292 this.connected = connected;
295 private ListenableFuture<EffectiveModelContext> assembleSchemaContext(final DeviceSources deviceSources,
296 final NetconfSessionPreferences remoteSessionCapabilities) {
297 LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
298 final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
299 for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
300 sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
301 PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class,
302 PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
305 return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
308 private ListenableFuture<MountPointContext> createMountPointContext(final EffectiveModelContext schemaContext,
309 final BaseSchema baseSchema, final NetconfDeviceCommunicator listener) {
310 final MountPointContext emptyContext = new EmptyMountPointContext(schemaContext);
311 if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
312 return Futures.immediateFuture(emptyContext);
315 // Create a temporary RPC invoker and acquire the mount point tree
316 LOG.debug("{}: Acquiring available mount points", id);
317 final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
318 new NetconfMessageTransformer(emptyContext, false, baseSchema));
320 return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
321 Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
322 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
323 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
326 private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
327 final Collection<? extends RpcError> errors = rpcResult.getErrors();
328 if (!errors.isEmpty()) {
329 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
331 final NormalizedNode schemaMounts = rpcResult.getResult();
332 if (schemaMounts == null) {
333 LOG.debug("{}: device does not define any schema mounts", id);
336 if (!(schemaMounts instanceof ContainerNode)) {
337 LOG.warn("{}: ignoring non-container schema mounts {}", id, schemaMounts);
341 return DeviceMountPointContext.create(emptyContext, (ContainerNode) schemaMounts);
345 public void onRemoteSessionDown() {
347 notificationHandler.onRemoteSchemaDown();
349 salFacade.onDeviceDisconnected();
350 sourceRegistrations.forEach(SchemaSourceRegistration::close);
351 sourceRegistrations.clear();
352 resetMessageTransformer();
356 public void onRemoteSessionFailed(final Throwable throwable) {
358 salFacade.onDeviceFailed(throwable);
362 public void onNotification(final NetconfMessage notification) {
363 notificationHandler.handleNotification(notification);
366 private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
367 return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
370 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
371 final RemoteDeviceCommunicator<NetconfMessage> listener, final BaseSchema schema) {
372 return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
373 new NetconfMessageTransformer(result, true, schema));
377 * Just a transfer object containing schema related dependencies. Injected in constructor.
379 public static class SchemaResourcesDTO {
380 private final SchemaSourceRegistry schemaRegistry;
381 private final SchemaRepository schemaRepository;
382 private final EffectiveModelContextFactory schemaContextFactory;
383 private final NetconfDeviceSchemasResolver stateSchemasResolver;
385 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
386 final SchemaRepository schemaRepository,
387 final EffectiveModelContextFactory schemaContextFactory,
388 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
389 this.schemaRegistry = requireNonNull(schemaRegistry);
390 this.schemaRepository = requireNonNull(schemaRepository);
391 this.schemaContextFactory = requireNonNull(schemaContextFactory);
392 stateSchemasResolver = requireNonNull(deviceSchemasResolver);
395 public SchemaSourceRegistry getSchemaRegistry() {
396 return schemaRegistry;
399 public SchemaRepository getSchemaRepository() {
400 return schemaRepository;
403 public EffectiveModelContextFactory getSchemaContextFactory() {
404 return schemaContextFactory;
407 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
408 return stateSchemasResolver;
413 * A dedicated exception to indicate when we fail to setup a SchemaContext.
415 * @author Robert Varga
417 private static final class EmptySchemaContextException extends Exception {
418 private static final long serialVersionUID = 1L;
420 EmptySchemaContextException(final String message) {
426 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
428 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
429 private final SettableFuture<EffectiveModelContext> resultFuture = SettableFuture.create();
431 private final DeviceSources deviceSources;
432 private final NetconfSessionPreferences remoteSessionCapabilities;
433 private final NetconfDeviceCapabilities capabilities;
435 private Collection<SourceIdentifier> requiredSources;
437 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
438 this.deviceSources = deviceSources;
439 this.remoteSessionCapabilities = remoteSessionCapabilities;
440 capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
442 // If device supports notifications and does not contain necessary modules, add them automatically
443 if (remoteSessionCapabilities.containsNonModuleCapability(
444 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0)) {
445 deviceSources.getRequiredSourcesQName().addAll(
447 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
448 .$YangModuleInfoImpl.getInstance().getName(),
449 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
450 .$YangModuleInfoImpl.getInstance().getName()
455 requiredSources = deviceSources.getRequiredSources();
456 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
458 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
459 UnavailableCapability.FailureReason.MissingSource);
460 requiredSources.removeAll(missingSources);
463 ListenableFuture<EffectiveModelContext> startResolution() {
469 public void onSuccess(final EffectiveModelContext result) {
470 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
472 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
473 capabilities.getUnresolvedCapabilites().keySet());
474 capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
475 .setCapability(entry.toString()).setCapabilityOrigin(
476 remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
477 .collect(Collectors.toList()));
479 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
480 .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
481 .setCapability(entry).setCapabilityOrigin(
482 remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
483 .collect(Collectors.toList()));
485 resultFuture.set(result);
489 public void onFailure(final Throwable cause) {
490 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
491 // that might be wrapping a MissingSchemaSourceException so we need to look
492 // at the cause of the exception to make sure we don't misinterpret it.
493 if (cause instanceof MissingSchemaSourceException) {
494 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
495 } else if (cause instanceof SchemaResolutionException) {
496 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
498 LOG.debug("Unhandled failure", cause);
499 resultFuture.setException(cause);
507 private void trySetupSchema() {
508 if (!requiredSources.isEmpty()) {
509 // Initiate async resolution, drive it back based on the result
510 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
511 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
512 MoreExecutors.directExecutor());
514 LOG.debug("{}: no more sources for schema context", id);
515 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
519 private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
520 return origSources.parallelStream().filter(sourceIdentifier -> {
522 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
524 } catch (InterruptedException | ExecutionException e) {
527 }).collect(Collectors.toList());
530 private Collection<SourceIdentifier> handleMissingSchemaSourceException(
531 final MissingSchemaSourceException exception) {
532 // In case source missing, try without it
533 final SourceIdentifier missingSource = exception.getSourceId();
534 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
536 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
537 id, missingSource, exception);
538 final Collection<QName> qNameOfMissingSource =
539 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
540 if (!qNameOfMissingSource.isEmpty()) {
541 capabilities.addUnresolvedCapabilities(
542 qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
544 return stripUnavailableSource(missingSource);
547 private Collection<SourceIdentifier> handleSchemaResolutionException(
548 final SchemaResolutionException resolutionException) {
549 // In case resolution error, try only with resolved sources
550 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
551 // FIXME Do we really have assurance that these two cases cannot happen at once?
552 if (resolutionException.getFailedSource() != null) {
553 // flawed model - exclude it
554 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
555 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
557 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
558 id, failedSourceId, resolutionException);
559 capabilities.addUnresolvedCapabilities(
560 getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
561 UnavailableCapability.FailureReason.UnableToResolve);
562 return stripUnavailableSource(resolutionException.getFailedSource());
564 // unsatisfied imports
565 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
566 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
567 UnavailableCapability.FailureReason.UnableToResolve);
568 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
569 id, resolutionException.getUnsatisfiedImports());
570 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
571 id, resolutionException.getUnsatisfiedImports(), resolutionException);
572 return resolutionException.getResolvedSources();
575 private Collection<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
576 final LinkedList<SourceIdentifier> sourceIdentifiers = new LinkedList<>(requiredSources);
577 checkState(sourceIdentifiers.remove(sourceIdToRemove),
578 "%s: Trying to remove %s from %s failed", id, sourceIdToRemove, requiredSources);
579 return sourceIdentifiers;
582 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
583 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
585 if (qNames.isEmpty()) {
586 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
589 return Collections2.filter(qNames, Predicates.notNull());
592 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
593 // Required sources are all required and provided merged in DeviceSourcesResolver
594 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
595 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
599 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
603 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
604 deviceSources.getRequiredSourcesQName());
605 // return null since we cannot find the QName,
606 // this capability will be removed from required sources and not reported as unresolved-capability