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.CancellationException;
35 import java.util.concurrent.ExecutionException;
36 import java.util.concurrent.TimeUnit;
37 import java.util.stream.Collectors;
38 import org.checkerframework.checker.lock.qual.GuardedBy;
39 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
40 import org.opendaylight.mdsal.dom.api.DOMRpcService;
41 import org.opendaylight.netconf.api.NetconfMessage;
42 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
43 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
44 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
45 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
46 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
47 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
48 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
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.netconf.sal.connect.util.RemoteDeviceId;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.optional.rev190614.NetconfNodeAugmentedOptional;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
63 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
64 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
65 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
66 import org.opendaylight.yangtools.yang.common.QName;
67 import org.opendaylight.yangtools.yang.common.RpcError;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
72 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
73 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
74 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
75 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
76 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
77 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
78 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
79 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
80 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
81 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
82 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
83 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
88 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
90 public class NetconfDevice
91 implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
93 @SuppressFBWarnings(value = "SLF4J_LOGGER_SHOULD_BE_PRIVATE",
94 justification = "Needed for common logging of related classes")
95 static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
97 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
98 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
99 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
100 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
102 protected final RemoteDeviceId id;
103 protected final EffectiveModelContextFactory schemaContextFactory;
104 protected final SchemaSourceRegistry schemaRegistry;
105 protected final SchemaRepository schemaRepository;
107 protected final List<SchemaSourceRegistration<?>> sourceRegistrations = new ArrayList<>();
109 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
110 private final ListeningExecutorService processingExecutor;
111 private final DeviceActionFactory deviceActionFactory;
112 private final NetconfDeviceSchemasResolver stateSchemasResolver;
113 private final NotificationHandler notificationHandler;
114 private final boolean reconnectOnSchemasChange;
115 private final BaseNetconfSchemas baseSchemas;
116 private final NetconfNode node;
117 private final EventExecutor eventExecutor;
118 private final NetconfNodeAugmentedOptional nodeOptional;
121 private ListenableFuture<List<Object>> schemaFuturesList;
123 private boolean connected = false;
125 // Message transformer is constructed once the schemas are available
126 private MessageTransformer<NetconfMessage> messageTransformer;
128 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
129 final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
130 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
131 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null,
135 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
136 final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
137 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
138 final DeviceActionFactory deviceActionFactory, final NetconfNode node, final EventExecutor eventExecutor,
139 final NetconfNodeAugmentedOptional nodeOptional) {
140 this.baseSchemas = requireNonNull(baseSchemas);
142 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
143 this.deviceActionFactory = deviceActionFactory;
145 this.eventExecutor = eventExecutor;
146 this.nodeOptional = nodeOptional;
147 schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
148 schemaRepository = schemaResourcesDTO.getSchemaRepository();
149 schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
150 this.salFacade = salFacade;
151 stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
152 processingExecutor = requireNonNull(globalProcessingExecutor);
153 notificationHandler = new NotificationHandler(salFacade, id);
157 public synchronized void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
158 final NetconfDeviceCommunicator listener) {
159 // SchemaContext setup has to be performed in a dedicated thread since
160 // we are in a netty thread in this method
161 // Yang models are being downloaded in this method and it would cause a
162 // deadlock if we used the netty thread
163 // http://netty.io/wiki/thread-model.html
165 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
167 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
168 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
169 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
170 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
171 new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
173 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
174 registerToBaseNetconfStream(initRpc, listener);
177 // Set up the SchemaContext for the device
178 final ListenableFuture<EffectiveModelContext> futureSchema = Futures.transformAsync(sourceResolverFuture,
179 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
181 // Potentially acquire mount point list and interpret it
182 final ListenableFuture<MountPointContext> futureContext = Futures.transformAsync(futureSchema,
183 schemaContext -> createMountPointContext(schemaContext, baseSchema, listener), processingExecutor);
184 schemaFuturesList = Futures.allAsList(sourceResolverFuture, futureSchema, futureContext);
186 Futures.addCallback(futureContext, new FutureCallback<MountPointContext>() {
188 public void onSuccess(final MountPointContext result) {
189 handleSalInitializationSuccess(result, remoteSessionCapabilities,
190 getDeviceSpecificRpc(result, listener, baseSchema), listener);
194 public void onFailure(final Throwable cause) {
195 if (cause instanceof CancellationException) {
196 LOG.warn("{}: Device communicator was tear down since the schema setup started", id);
200 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
201 // No more sources, fail or try to reconnect
202 if (cause instanceof EmptySchemaContextException) {
203 if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().getAllowed()) {
204 eventExecutor.schedule(() -> {
205 LOG.warn("Reconnection is allowed! This can lead to unexpected errors at runtime.");
206 LOG.warn("{} : No more sources for schema context.", id);
207 LOG.info("{} : Try to remount device.", id);
208 onRemoteSessionDown();
209 salFacade.onDeviceReconnected(remoteSessionCapabilities, node);
210 }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime().toJava(),
211 TimeUnit.MILLISECONDS);
216 handleSalInitializationFailure(cause, listener);
217 salFacade.onDeviceFailed(cause);
219 }, MoreExecutors.directExecutor());
222 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
223 final NetconfDeviceCommunicator listener) {
224 // TODO check whether the model describing create subscription is present in schema
225 // Perhaps add a default schema context to support create-subscription if the model was not provided
226 // (same as what we do for base netconf operations in transformer)
227 final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
228 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
229 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
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().getIdentifier().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();
240 return Optional.empty();
242 return Optional.of(notification);
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 MountPointContext result,
259 final NetconfSessionPreferences remoteSessionCapabilities,
260 final DOMRpcService deviceRpc,
261 final RemoteDeviceCommunicator<NetconfMessage> listener) {
262 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
263 //since salFacade.onDeviceDisconnected was already called.
265 messageTransformer = new NetconfMessageTransformer(result, true,
266 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
268 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
269 salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
270 deviceActionFactory == null ? null : deviceActionFactory.createDeviceAction(
271 messageTransformer, listener, result.getEffectiveModelContext()));
272 notificationHandler.onRemoteSchemaUp(messageTransformer);
274 LOG.info("{}: Netconf connector initialized successfully", id);
276 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
280 private void handleSalInitializationFailure(final Throwable throwable,
281 final RemoteDeviceCommunicator<NetconfMessage> listener) {
282 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
284 onRemoteSessionDown();
285 resetMessageTransformer();
289 * Set the transformer to null as is in initial state.
291 private void resetMessageTransformer() {
292 updateTransformer(null);
295 private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
296 messageTransformer = transformer;
299 private synchronized void setConnected(final boolean connected) {
300 this.connected = connected;
303 private ListenableFuture<EffectiveModelContext> assembleSchemaContext(final DeviceSources deviceSources,
304 final NetconfSessionPreferences remoteSessionCapabilities) {
305 LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
306 final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
307 for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
308 sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
309 PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class,
310 PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
313 return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
316 private ListenableFuture<MountPointContext> createMountPointContext(final EffectiveModelContext schemaContext,
317 final BaseSchema baseSchema, final NetconfDeviceCommunicator listener) {
318 final MountPointContext emptyContext = new EmptyMountPointContext(schemaContext);
319 if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
320 return Futures.immediateFuture(emptyContext);
323 // Create a temporary RPC invoker and acquire the mount point tree
324 LOG.debug("{}: Acquiring available mount points", id);
325 final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
326 new NetconfMessageTransformer(emptyContext, false, baseSchema));
328 return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
329 Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
330 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
331 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
334 private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
335 final Collection<? extends RpcError> errors = rpcResult.getErrors();
336 if (!errors.isEmpty()) {
337 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
339 final NormalizedNode schemaMounts = rpcResult.getResult();
340 if (schemaMounts == null) {
341 LOG.debug("{}: device does not define any schema mounts", id);
344 if (!(schemaMounts instanceof ContainerNode)) {
345 LOG.warn("{}: ignoring non-container schema mounts {}", id, schemaMounts);
349 return DeviceMountPointContext.create(emptyContext, (ContainerNode) schemaMounts);
353 public synchronized void onRemoteSessionDown() {
355 if (schemaFuturesList != null && !schemaFuturesList.isDone()) {
356 if (!schemaFuturesList.cancel(true)) {
357 LOG.warn("The cleanup of Schema Futures for device {} was unsuccessful.", id);
360 notificationHandler.onRemoteSchemaDown();
361 salFacade.onDeviceDisconnected();
362 sourceRegistrations.forEach(SchemaSourceRegistration::close);
363 sourceRegistrations.clear();
364 resetMessageTransformer();
368 public void onRemoteSessionFailed(final Throwable throwable) {
370 salFacade.onDeviceFailed(throwable);
374 public void onNotification(final NetconfMessage notification) {
375 notificationHandler.handleNotification(notification);
378 private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
379 return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
382 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
383 final RemoteDeviceCommunicator<NetconfMessage> listener, final BaseSchema schema) {
384 return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
385 new NetconfMessageTransformer(result, true, schema));
389 * Just a transfer object containing schema related dependencies. Injected in constructor.
391 public static class SchemaResourcesDTO {
392 private final SchemaSourceRegistry schemaRegistry;
393 private final SchemaRepository schemaRepository;
394 private final EffectiveModelContextFactory schemaContextFactory;
395 private final NetconfDeviceSchemasResolver stateSchemasResolver;
397 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
398 final SchemaRepository schemaRepository,
399 final EffectiveModelContextFactory schemaContextFactory,
400 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
401 this.schemaRegistry = requireNonNull(schemaRegistry);
402 this.schemaRepository = requireNonNull(schemaRepository);
403 this.schemaContextFactory = requireNonNull(schemaContextFactory);
404 stateSchemasResolver = requireNonNull(deviceSchemasResolver);
407 public SchemaSourceRegistry getSchemaRegistry() {
408 return schemaRegistry;
411 public SchemaRepository getSchemaRepository() {
412 return schemaRepository;
415 public EffectiveModelContextFactory getSchemaContextFactory() {
416 return schemaContextFactory;
419 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
420 return stateSchemasResolver;
425 * A dedicated exception to indicate when we fail to setup a SchemaContext.
427 * @author Robert Varga
429 private static final class EmptySchemaContextException extends Exception {
430 private static final long serialVersionUID = 1L;
432 EmptySchemaContextException(final String message) {
438 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
440 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
441 private final SettableFuture<EffectiveModelContext> resultFuture = SettableFuture.create();
443 private final DeviceSources deviceSources;
444 private final NetconfSessionPreferences remoteSessionCapabilities;
445 private final NetconfDeviceCapabilities capabilities;
447 private Collection<SourceIdentifier> requiredSources;
449 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
450 this.deviceSources = deviceSources;
451 this.remoteSessionCapabilities = remoteSessionCapabilities;
452 capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
454 // If device supports notifications and does not contain necessary modules, add them automatically
455 if (remoteSessionCapabilities.containsNonModuleCapability(
456 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0)) {
457 deviceSources.getRequiredSourcesQName().addAll(
459 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
460 .$YangModuleInfoImpl.getInstance().getName(),
461 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
462 .$YangModuleInfoImpl.getInstance().getName()
467 requiredSources = deviceSources.getRequiredSources();
468 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
470 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
471 UnavailableCapability.FailureReason.MissingSource);
472 requiredSources.removeAll(missingSources);
475 ListenableFuture<EffectiveModelContext> startResolution() {
481 public void onSuccess(final EffectiveModelContext result) {
482 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
484 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
485 capabilities.getUnresolvedCapabilites().keySet());
486 capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
487 .setCapability(entry.toString()).setCapabilityOrigin(
488 remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
489 .collect(Collectors.toList()));
491 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
492 .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
493 .setCapability(entry).setCapabilityOrigin(
494 remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
495 .collect(Collectors.toList()));
497 resultFuture.set(result);
501 public void onFailure(final Throwable cause) {
502 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
503 // that might be wrapping a MissingSchemaSourceException so we need to look
504 // at the cause of the exception to make sure we don't misinterpret it.
505 if (cause instanceof MissingSchemaSourceException) {
506 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
507 } else if (cause instanceof SchemaResolutionException) {
508 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
510 LOG.debug("Unhandled failure", cause);
511 resultFuture.setException(cause);
519 private void trySetupSchema() {
520 if (!requiredSources.isEmpty()) {
521 // Initiate async resolution, drive it back based on the result
522 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
523 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
524 MoreExecutors.directExecutor());
526 LOG.debug("{}: no more sources for schema context", id);
527 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
531 private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
532 return origSources.parallelStream().filter(sourceIdentifier -> {
534 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
536 } catch (InterruptedException | ExecutionException e) {
539 }).collect(Collectors.toList());
542 private Collection<SourceIdentifier> handleMissingSchemaSourceException(
543 final MissingSchemaSourceException exception) {
544 // In case source missing, try without it
545 final SourceIdentifier missingSource = exception.getSourceId();
546 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
548 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
549 id, missingSource, exception);
550 final Collection<QName> qNameOfMissingSource =
551 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
552 if (!qNameOfMissingSource.isEmpty()) {
553 capabilities.addUnresolvedCapabilities(
554 qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
556 return stripUnavailableSource(missingSource);
559 private Collection<SourceIdentifier> handleSchemaResolutionException(
560 final SchemaResolutionException resolutionException) {
561 // In case resolution error, try only with resolved sources
562 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
563 // FIXME Do we really have assurance that these two cases cannot happen at once?
564 if (resolutionException.getFailedSource() != null) {
565 // flawed model - exclude it
566 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
567 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
569 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
570 id, failedSourceId, resolutionException);
571 capabilities.addUnresolvedCapabilities(
572 getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
573 UnavailableCapability.FailureReason.UnableToResolve);
574 return stripUnavailableSource(resolutionException.getFailedSource());
576 // unsatisfied imports
577 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
578 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
579 UnavailableCapability.FailureReason.UnableToResolve);
580 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
581 id, resolutionException.getUnsatisfiedImports());
582 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
583 id, resolutionException.getUnsatisfiedImports(), resolutionException);
584 return resolutionException.getResolvedSources();
587 private Collection<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
588 final LinkedList<SourceIdentifier> sourceIdentifiers = new LinkedList<>(requiredSources);
589 checkState(sourceIdentifiers.remove(sourceIdToRemove),
590 "%s: Trying to remove %s from %s failed", id, sourceIdToRemove, requiredSources);
591 return sourceIdentifiers;
594 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
595 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
597 if (qNames.isEmpty()) {
598 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
601 return Collections2.filter(qNames, Predicates.notNull());
604 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
605 // Required sources are all required and provided merged in DeviceSourcesResolver
606 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
607 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
611 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
615 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
616 deviceSources.getRequiredSourcesQName());
617 // return null since we cannot find the QName,
618 // this capability will be removed from required sources and not reported as unresolved-capability