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.Collection;
27 import java.util.Collections;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.Optional;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.TimeUnit;
34 import java.util.stream.Collectors;
35 import org.checkerframework.checker.lock.qual.GuardedBy;
36 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
37 import org.opendaylight.mdsal.dom.api.DOMRpcService;
38 import org.opendaylight.netconf.api.NetconfMessage;
39 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
40 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
41 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
42 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
43 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
44 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
45 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
47 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
48 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
49 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseNetconfSchemas;
50 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
51 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
52 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
53 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.optional.rev190614.NetconfNodeAugmentedOptional;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
59 import org.opendaylight.yangtools.rcf8528.data.util.EmptyMountPointContext;
60 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
61 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
62 import org.opendaylight.yangtools.yang.common.QName;
63 import org.opendaylight.yangtools.yang.common.RpcError;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
68 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
69 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
70 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
71 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
72 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
73 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
74 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
75 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
76 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
77 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
78 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
79 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
84 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
86 public class NetconfDevice
87 implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
89 @SuppressFBWarnings(value = "SLF4J_LOGGER_SHOULD_BE_PRIVATE",
90 justification = "Needed for common logging of related classes")
91 static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
93 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
94 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
95 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
96 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
98 protected final RemoteDeviceId id;
99 protected final EffectiveModelContextFactory schemaContextFactory;
100 protected final SchemaSourceRegistry schemaRegistry;
101 protected final SchemaRepository schemaRepository;
103 protected final List<SchemaSourceRegistration<?>> sourceRegistrations = new ArrayList<>();
105 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
106 private final ListeningExecutorService processingExecutor;
107 private final DeviceActionFactory deviceActionFactory;
108 private final NetconfDeviceSchemasResolver stateSchemasResolver;
109 private final NotificationHandler notificationHandler;
110 private final boolean reconnectOnSchemasChange;
111 private final BaseNetconfSchemas baseSchemas;
112 private final NetconfNode node;
113 private final EventExecutor eventExecutor;
114 private final NetconfNodeAugmentedOptional nodeOptional;
117 private boolean connected = false;
119 // Message transformer is constructed once the schemas are available
120 private MessageTransformer<NetconfMessage> messageTransformer;
122 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
123 final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
124 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
125 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null,
129 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
130 final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
131 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
132 final DeviceActionFactory deviceActionFactory, final NetconfNode node, final EventExecutor eventExecutor,
133 final NetconfNodeAugmentedOptional nodeOptional) {
134 this.baseSchemas = requireNonNull(baseSchemas);
136 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
137 this.deviceActionFactory = deviceActionFactory;
139 this.eventExecutor = eventExecutor;
140 this.nodeOptional = nodeOptional;
141 this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
142 this.schemaRepository = schemaResourcesDTO.getSchemaRepository();
143 this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
144 this.salFacade = salFacade;
145 this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
146 this.processingExecutor = requireNonNull(globalProcessingExecutor);
147 this.notificationHandler = new NotificationHandler(salFacade, id);
151 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
152 final NetconfDeviceCommunicator listener) {
153 // SchemaContext setup has to be performed in a dedicated thread since
154 // we are in a netty thread in this method
155 // Yang models are being downloaded in this method and it would cause a
156 // deadlock if we used the netty thread
157 // http://netty.io/wiki/thread-model.html
159 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
161 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
162 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener,
163 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
164 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
165 new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
167 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
168 registerToBaseNetconfStream(initRpc, listener);
171 // Set up the SchemaContext for the device
172 final ListenableFuture<EffectiveModelContext> futureSchema = Futures.transformAsync(sourceResolverFuture,
173 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
175 // Potentially acquire mount point list and interpret it
176 final ListenableFuture<MountPointContext> futureContext = Futures.transformAsync(futureSchema,
177 schemaContext -> createMountPointContext(schemaContext, baseSchema, listener), processingExecutor);
179 Futures.addCallback(futureContext, new FutureCallback<MountPointContext>() {
181 public void onSuccess(final MountPointContext result) {
182 handleSalInitializationSuccess(result, remoteSessionCapabilities,
183 getDeviceSpecificRpc(result, listener), listener);
187 public void onFailure(final Throwable cause) {
188 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
190 // No more sources, fail or try to reconnect
191 if (cause instanceof EmptySchemaContextException) {
192 if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().isAllowed()) {
193 eventExecutor.schedule(() -> {
194 LOG.warn("Reconnection is allowed! This can lead to unexpected errors at runtime.");
195 LOG.warn("{} : No more sources for schema context.", id);
196 LOG.info("{} : Try to remount device.", id);
197 onRemoteSessionDown();
198 salFacade.onDeviceReconnected(remoteSessionCapabilities, node);
199 }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime().toJava(),
200 TimeUnit.MILLISECONDS);
205 handleSalInitializationFailure(cause, listener);
206 salFacade.onDeviceFailed(cause);
208 }, MoreExecutors.directExecutor());
211 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
212 final NetconfDeviceCommunicator listener) {
213 // TODO check whether the model describing create subscription is present in schema
214 // Perhaps add a default schema context to support create-subscription if the model was not provided
215 // (same as what we do for base netconf operations in transformer)
216 final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
217 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_PATH,
218 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
220 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
222 public void onSuccess(final DOMRpcResult domRpcResult) {
223 notificationHandler.addNotificationFilter(notification -> {
224 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getNodeType())) {
225 LOG.info("{}: Schemas change detected, reconnecting", id);
226 // Only disconnect is enough,
227 // the reconnecting nature of the connector will take care of reconnecting
228 listener.disconnect();
229 return Optional.empty();
231 return Optional.of(notification);
236 public void onFailure(final Throwable throwable) {
237 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
240 }, MoreExecutors.directExecutor());
243 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
244 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
247 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
248 justification = "https://github.com/spotbugs/spotbugs/issues/811")
249 private synchronized void handleSalInitializationSuccess(final MountPointContext result,
250 final NetconfSessionPreferences remoteSessionCapabilities,
251 final DOMRpcService deviceRpc,
252 final RemoteDeviceCommunicator<NetconfMessage> listener) {
253 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
254 //since salFacade.onDeviceDisconnected was already called.
256 this.messageTransformer = new NetconfMessageTransformer(result, true,
257 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
259 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
260 this.salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
261 this.deviceActionFactory == null ? null : this.deviceActionFactory.createDeviceAction(
262 this.messageTransformer, listener, result.getSchemaContext()));
263 this.notificationHandler.onRemoteSchemaUp(this.messageTransformer);
265 LOG.info("{}: Netconf connector initialized successfully", id);
267 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
271 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
272 justification = "https://github.com/spotbugs/spotbugs/issues/811")
273 private void handleSalInitializationFailure(final Throwable throwable,
274 final RemoteDeviceCommunicator<NetconfMessage> listener) {
275 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
277 onRemoteSessionDown();
278 resetMessageTransformer();
282 * Set the transformer to null as is in initial state.
284 private void resetMessageTransformer() {
285 updateTransformer(null);
288 private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
289 messageTransformer = transformer;
292 private synchronized void setConnected(final boolean connected) {
293 this.connected = connected;
296 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
297 justification = "https://github.com/spotbugs/spotbugs/issues/811")
298 private ListenableFuture<EffectiveModelContext> assembleSchemaContext(final DeviceSources deviceSources,
299 final NetconfSessionPreferences remoteSessionCapabilities) {
300 LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
301 final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
302 for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
303 sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
304 PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class,
305 PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
308 return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
311 private ListenableFuture<MountPointContext> createMountPointContext(final EffectiveModelContext schemaContext,
312 final BaseSchema baseSchema, final NetconfDeviceCommunicator listener) {
313 final MountPointContext emptyContext = new EmptyMountPointContext(schemaContext);
314 if (!schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isPresent()) {
315 return Futures.immediateFuture(emptyContext);
318 // Create a temporary RPC invoker and acquire the mount point tree
319 LOG.debug("{}: Acquiring available mount points", id);
320 final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
321 new NetconfMessageTransformer(emptyContext, false, baseSchema));
323 return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_PATH,
324 Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
325 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
326 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
329 private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
330 final Collection<? extends RpcError> errors = rpcResult.getErrors();
331 if (!errors.isEmpty()) {
332 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
334 final NormalizedNode<?, ?> schemaMounts = rpcResult.getResult();
335 if (schemaMounts == null) {
336 LOG.debug("{}: device does not define any schema mounts", id);
339 if (!(schemaMounts instanceof ContainerNode)) {
340 LOG.warn("{}: ignoring non-container schema mounts {}", id, schemaMounts);
344 return DeviceMountPointContext.create(emptyContext, (ContainerNode) schemaMounts);
348 public void onRemoteSessionDown() {
350 notificationHandler.onRemoteSchemaDown();
352 salFacade.onDeviceDisconnected();
353 sourceRegistrations.forEach(SchemaSourceRegistration::close);
354 sourceRegistrations.clear();
355 resetMessageTransformer();
359 public void onRemoteSessionFailed(final Throwable throwable) {
361 salFacade.onDeviceFailed(throwable);
365 public void onNotification(final NetconfMessage notification) {
366 notificationHandler.handleNotification(notification);
369 private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
370 return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
373 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
374 final RemoteDeviceCommunicator<NetconfMessage> listener) {
375 return new NetconfDeviceRpc(result.getSchemaContext(), listener,
376 new NetconfMessageTransformer(result, true, baseSchemas.getBaseSchema()));
380 * Just a transfer object containing schema related dependencies. Injected in constructor.
382 public static class SchemaResourcesDTO {
383 private final SchemaSourceRegistry schemaRegistry;
384 private final SchemaRepository schemaRepository;
385 private final EffectiveModelContextFactory schemaContextFactory;
386 private final NetconfDeviceSchemasResolver stateSchemasResolver;
388 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
389 final SchemaRepository schemaRepository,
390 final EffectiveModelContextFactory schemaContextFactory,
391 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
392 this.schemaRegistry = requireNonNull(schemaRegistry);
393 this.schemaRepository = requireNonNull(schemaRepository);
394 this.schemaContextFactory = requireNonNull(schemaContextFactory);
395 this.stateSchemasResolver = requireNonNull(deviceSchemasResolver);
398 public SchemaSourceRegistry getSchemaRegistry() {
399 return schemaRegistry;
402 public SchemaRepository getSchemaRepository() {
403 return schemaRepository;
406 public EffectiveModelContextFactory getSchemaContextFactory() {
407 return schemaContextFactory;
410 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
411 return stateSchemasResolver;
416 * A dedicated exception to indicate when we fail to setup a SchemaContext.
418 * @author Robert Varga
420 private static final class EmptySchemaContextException extends Exception {
421 private static final long serialVersionUID = 1L;
423 EmptySchemaContextException(final String message) {
429 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
431 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
432 private final SettableFuture<EffectiveModelContext> resultFuture = SettableFuture.create();
434 private final DeviceSources deviceSources;
435 private final NetconfSessionPreferences remoteSessionCapabilities;
436 private final NetconfDeviceCapabilities capabilities;
438 private Collection<SourceIdentifier> requiredSources;
440 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
441 this.deviceSources = deviceSources;
442 this.remoteSessionCapabilities = remoteSessionCapabilities;
443 this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
445 requiredSources = deviceSources.getRequiredSources();
446 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
448 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
449 UnavailableCapability.FailureReason.MissingSource);
450 requiredSources.removeAll(missingSources);
453 ListenableFuture<EffectiveModelContext> startResolution() {
459 public void onSuccess(final EffectiveModelContext result) {
460 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
462 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
463 capabilities.getUnresolvedCapabilites().keySet());
464 capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
465 .setCapability(entry.toString()).setCapabilityOrigin(
466 remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
467 .collect(Collectors.toList()));
469 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
470 .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
471 .setCapability(entry).setCapabilityOrigin(
472 remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
473 .collect(Collectors.toList()));
475 resultFuture.set(result);
479 public void onFailure(final Throwable cause) {
480 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
481 // that might be wrapping a MissingSchemaSourceException so we need to look
482 // at the cause of the exception to make sure we don't misinterpret it.
483 if (cause instanceof MissingSchemaSourceException) {
484 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
485 } else if (cause instanceof SchemaResolutionException) {
486 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
488 LOG.debug("Unhandled failure", cause);
489 resultFuture.setException(cause);
497 private void trySetupSchema() {
498 if (!requiredSources.isEmpty()) {
499 // Initiate async resolution, drive it back based on the result
500 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
501 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
502 MoreExecutors.directExecutor());
504 LOG.debug("{}: no more sources for schema context", id);
505 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
509 private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
510 return origSources.parallelStream().filter(sourceIdentifier -> {
512 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
514 } catch (InterruptedException | ExecutionException e) {
517 }).collect(Collectors.toList());
520 private Collection<SourceIdentifier> handleMissingSchemaSourceException(
521 final MissingSchemaSourceException exception) {
522 // In case source missing, try without it
523 final SourceIdentifier missingSource = exception.getSourceId();
524 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
526 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
527 id, missingSource, exception);
528 final Collection<QName> qNameOfMissingSource =
529 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
530 if (!qNameOfMissingSource.isEmpty()) {
531 capabilities.addUnresolvedCapabilities(
532 qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
534 return stripUnavailableSource(missingSource);
537 private Collection<SourceIdentifier> handleSchemaResolutionException(
538 final SchemaResolutionException resolutionException) {
539 // In case resolution error, try only with resolved sources
540 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
541 // FIXME Do we really have assurance that these two cases cannot happen at once?
542 if (resolutionException.getFailedSource() != null) {
543 // flawed model - exclude it
544 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
545 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
547 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
548 id, failedSourceId, resolutionException);
549 capabilities.addUnresolvedCapabilities(
550 getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
551 UnavailableCapability.FailureReason.UnableToResolve);
552 return stripUnavailableSource(resolutionException.getFailedSource());
554 // unsatisfied imports
555 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
556 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
557 UnavailableCapability.FailureReason.UnableToResolve);
558 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
559 id, resolutionException.getUnsatisfiedImports());
560 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
561 id, resolutionException.getUnsatisfiedImports(), resolutionException);
562 return resolutionException.getResolvedSources();
565 private Collection<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
566 final LinkedList<SourceIdentifier> sourceIdentifiers = new LinkedList<>(requiredSources);
567 checkState(sourceIdentifiers.remove(sourceIdToRemove),
568 "%s: Trying to remove %s from %s failed", id, sourceIdToRemove, requiredSources);
569 return sourceIdentifiers;
572 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
573 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
575 if (qNames.isEmpty()) {
576 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
579 return Collections2.filter(qNames, Predicates.notNull());
582 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
583 // Required sources are all required and provided merged in DeviceSourcesResolver
584 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
585 if (!qname.getLocalName().equals(identifier.getName())) {
589 if (identifier.getRevision().equals(qname.getRevision())) {
593 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
594 deviceSources.getRequiredSourcesQName());
595 // return null since we cannot find the QName,
596 // this capability will be removed from required sources and not reported as unresolved-capability