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.BaseSchema;
50 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
51 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
52 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
53 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.optional.rev190614.NetconfNodeAugmentedOptional;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
58 import org.opendaylight.yangtools.rcf8528.data.util.EmptyMountPointContext;
59 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
60 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
61 import org.opendaylight.yangtools.yang.common.QName;
62 import org.opendaylight.yangtools.yang.common.RpcError;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
67 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
68 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
69 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
70 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
71 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
72 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
73 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
74 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
75 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
76 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
77 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
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
86 implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
88 @SuppressFBWarnings(value = "SLF4J_LOGGER_SHOULD_BE_PRIVATE",
89 justification = "Needed for common logging of related classes")
90 static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
92 private static final QName RFC8528_SCHEMA_MOUNTS_QNAME = QName.create(
93 SchemaMountConstants.RFC8528_MODULE, "schema-mounts").intern();
94 private static final YangInstanceIdentifier RFC8528_SCHEMA_MOUNTS = YangInstanceIdentifier.create(
95 NodeIdentifier.create(RFC8528_SCHEMA_MOUNTS_QNAME));
97 protected final RemoteDeviceId id;
98 protected final EffectiveModelContextFactory schemaContextFactory;
99 protected final SchemaSourceRegistry schemaRegistry;
100 protected final SchemaRepository schemaRepository;
102 protected final List<SchemaSourceRegistration<?>> sourceRegistrations = new ArrayList<>();
104 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
105 private final ListeningExecutorService processingExecutor;
106 private final DeviceActionFactory deviceActionFactory;
107 private final NetconfDeviceSchemasResolver stateSchemasResolver;
108 private final NotificationHandler notificationHandler;
109 private final boolean reconnectOnSchemasChange;
110 private final NetconfNode node;
111 private final EventExecutor eventExecutor;
112 private final NetconfNodeAugmentedOptional nodeOptional;
115 private boolean connected = false;
117 // Message transformer is constructed once the schemas are available
118 private MessageTransformer<NetconfMessage> messageTransformer;
120 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
121 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
122 final ListeningExecutorService globalProcessingExecutor,
123 final boolean reconnectOnSchemasChange) {
124 this(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null, null, null,
128 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
129 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
130 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
131 final DeviceActionFactory deviceActionFactory, final NetconfNode node, final EventExecutor eventExecutor,
132 final NetconfNodeAugmentedOptional nodeOptional) {
134 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
135 this.deviceActionFactory = deviceActionFactory;
137 this.eventExecutor = eventExecutor;
138 this.nodeOptional = nodeOptional;
139 this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
140 this.schemaRepository = schemaResourcesDTO.getSchemaRepository();
141 this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
142 this.salFacade = salFacade;
143 this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
144 this.processingExecutor = requireNonNull(globalProcessingExecutor);
145 this.notificationHandler = new NotificationHandler(salFacade, id);
149 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
150 final NetconfDeviceCommunicator listener) {
151 // SchemaContext setup has to be performed in a dedicated thread since
152 // we are in a netty thread in this method
153 // Yang models are being downloaded in this method and it would cause a
154 // deadlock if we used the netty thread
155 // http://netty.io/wiki/thread-model.html
157 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
159 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
160 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener,
161 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
162 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
163 new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
165 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
166 registerToBaseNetconfStream(initRpc, listener);
169 // Set up the SchemaContext for the device
170 final ListenableFuture<EffectiveModelContext> futureSchema = Futures.transformAsync(sourceResolverFuture,
171 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
173 // Potentially acquire mount point list and interpret it
174 final ListenableFuture<MountPointContext> futureContext = Futures.transformAsync(futureSchema,
175 schemaContext -> createMountPointContext(schemaContext, baseSchema, listener), processingExecutor);
177 Futures.addCallback(futureContext, new FutureCallback<MountPointContext>() {
179 public void onSuccess(final MountPointContext result) {
180 handleSalInitializationSuccess(result, remoteSessionCapabilities,
181 getDeviceSpecificRpc(result, listener), listener);
185 public void onFailure(final Throwable cause) {
186 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
188 // No more sources, fail or try to reconnect
189 if (cause instanceof EmptySchemaContextException) {
190 if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().isAllowed()) {
191 eventExecutor.schedule(() -> {
192 LOG.warn("Reconnection is allowed! This can lead to unexpected errors at runtime.");
193 LOG.warn("{} : No more sources for schema context.", id);
194 LOG.info("{} : Try to remount device.", id);
195 onRemoteSessionDown();
196 salFacade.onDeviceReconnected(remoteSessionCapabilities, node);
197 }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime().toJava(),
198 TimeUnit.MILLISECONDS);
203 handleSalInitializationFailure(cause, listener);
204 salFacade.onDeviceFailed(cause);
206 }, MoreExecutors.directExecutor());
209 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
210 final NetconfDeviceCommunicator listener) {
211 // TODO check whether the model describing create subscription is present in schema
212 // Perhaps add a default schema context to support create-subscription if the model was not provided
213 // (same as what we do for base netconf operations in transformer)
214 final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
215 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_PATH,
216 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
218 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
220 public void onSuccess(final DOMRpcResult domRpcResult) {
221 notificationHandler.addNotificationFilter(notification -> {
222 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getNodeType())) {
223 LOG.info("{}: Schemas change detected, reconnecting", id);
224 // Only disconnect is enough,
225 // the reconnecting nature of the connector will take care of reconnecting
226 listener.disconnect();
227 return Optional.empty();
229 return Optional.of(notification);
234 public void onFailure(final Throwable throwable) {
235 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
238 }, MoreExecutors.directExecutor());
241 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
242 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
245 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
246 justification = "https://github.com/spotbugs/spotbugs/issues/811")
247 private synchronized void handleSalInitializationSuccess(final MountPointContext result,
248 final NetconfSessionPreferences remoteSessionCapabilities,
249 final DOMRpcService deviceRpc,
250 final RemoteDeviceCommunicator<NetconfMessage> listener) {
251 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
252 //since salFacade.onDeviceDisconnected was already called.
254 final BaseSchema baseSchema =
255 remoteSessionCapabilities.isNotificationsSupported()
256 ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
257 this.messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
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 static BaseSchema resolveBaseSchema(final boolean notificationSupport) {
370 return notificationSupport ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
373 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
374 final RemoteDeviceCommunicator<NetconfMessage> listener) {
375 return new NetconfDeviceRpc(result.getSchemaContext(), listener, new NetconfMessageTransformer(result, true));
379 * Just a transfer object containing schema related dependencies. Injected in constructor.
381 public static class SchemaResourcesDTO {
382 private final SchemaSourceRegistry schemaRegistry;
383 private final SchemaRepository schemaRepository;
384 private final EffectiveModelContextFactory schemaContextFactory;
385 private final NetconfDeviceSchemasResolver stateSchemasResolver;
387 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
388 final SchemaRepository schemaRepository,
389 final EffectiveModelContextFactory schemaContextFactory,
390 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
391 this.schemaRegistry = requireNonNull(schemaRegistry);
392 this.schemaRepository = requireNonNull(schemaRepository);
393 this.schemaContextFactory = requireNonNull(schemaContextFactory);
394 this.stateSchemasResolver = requireNonNull(deviceSchemasResolver);
397 public SchemaSourceRegistry getSchemaRegistry() {
398 return schemaRegistry;
401 public SchemaRepository getSchemaRepository() {
402 return schemaRepository;
405 public EffectiveModelContextFactory getSchemaContextFactory() {
406 return schemaContextFactory;
409 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
410 return stateSchemasResolver;
415 * A dedicated exception to indicate when we fail to setup a SchemaContext.
417 * @author Robert Varga
419 private static final class EmptySchemaContextException extends Exception {
420 private static final long serialVersionUID = 1L;
422 EmptySchemaContextException(final String message) {
428 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
430 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
431 private final SettableFuture<EffectiveModelContext> resultFuture = SettableFuture.create();
433 private final DeviceSources deviceSources;
434 private final NetconfSessionPreferences remoteSessionCapabilities;
435 private final NetconfDeviceCapabilities capabilities;
437 private Collection<SourceIdentifier> requiredSources;
439 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
440 this.deviceSources = deviceSources;
441 this.remoteSessionCapabilities = remoteSessionCapabilities;
442 this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
444 requiredSources = deviceSources.getRequiredSources();
445 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
447 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
448 UnavailableCapability.FailureReason.MissingSource);
449 requiredSources.removeAll(missingSources);
452 ListenableFuture<EffectiveModelContext> startResolution() {
458 public void onSuccess(final EffectiveModelContext result) {
459 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
461 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
462 capabilities.getUnresolvedCapabilites().keySet());
463 capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
464 .setCapability(entry.toString()).setCapabilityOrigin(
465 remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
466 .collect(Collectors.toList()));
468 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
469 .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
470 .setCapability(entry).setCapabilityOrigin(
471 remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
472 .collect(Collectors.toList()));
474 resultFuture.set(result);
478 public void onFailure(final Throwable cause) {
479 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
480 // that might be wrapping a MissingSchemaSourceException so we need to look
481 // at the cause of the exception to make sure we don't misinterpret it.
482 if (cause instanceof MissingSchemaSourceException) {
483 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
484 } else if (cause instanceof SchemaResolutionException) {
485 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
487 LOG.debug("Unhandled failure", cause);
488 resultFuture.setException(cause);
496 private void trySetupSchema() {
497 if (!requiredSources.isEmpty()) {
498 // Initiate async resolution, drive it back based on the result
499 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
500 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
501 MoreExecutors.directExecutor());
503 LOG.debug("{}: no more sources for schema context", id);
504 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
508 private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
509 return origSources.parallelStream().filter(sourceIdentifier -> {
511 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
513 } catch (InterruptedException | ExecutionException e) {
516 }).collect(Collectors.toList());
519 private Collection<SourceIdentifier> handleMissingSchemaSourceException(
520 final MissingSchemaSourceException exception) {
521 // In case source missing, try without it
522 final SourceIdentifier missingSource = exception.getSourceId();
523 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
525 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
526 id, missingSource, exception);
527 final Collection<QName> qNameOfMissingSource =
528 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
529 if (!qNameOfMissingSource.isEmpty()) {
530 capabilities.addUnresolvedCapabilities(
531 qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
533 return stripUnavailableSource(missingSource);
536 private Collection<SourceIdentifier> handleSchemaResolutionException(
537 final SchemaResolutionException resolutionException) {
538 // In case resolution error, try only with resolved sources
539 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
540 // FIXME Do we really have assurance that these two cases cannot happen at once?
541 if (resolutionException.getFailedSource() != null) {
542 // flawed model - exclude it
543 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
544 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
546 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
547 id, failedSourceId, resolutionException);
548 capabilities.addUnresolvedCapabilities(
549 getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
550 UnavailableCapability.FailureReason.UnableToResolve);
551 return stripUnavailableSource(resolutionException.getFailedSource());
553 // unsatisfied imports
554 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
555 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
556 UnavailableCapability.FailureReason.UnableToResolve);
557 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
558 id, resolutionException.getUnsatisfiedImports());
559 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
560 id, resolutionException.getUnsatisfiedImports(), resolutionException);
561 return resolutionException.getResolvedSources();
564 private Collection<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
565 final LinkedList<SourceIdentifier> sourceIdentifiers = new LinkedList<>(requiredSources);
566 checkState(sourceIdentifiers.remove(sourceIdToRemove),
567 "%s: Trying to remove %s from %s failed", id, sourceIdToRemove, requiredSources);
568 return sourceIdentifiers;
571 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
572 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
574 if (qNames.isEmpty()) {
575 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
578 return Collections2.filter(qNames, Predicates.notNull());
581 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
582 // Required sources are all required and provided merged in DeviceSourcesResolver
583 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
584 if (!qname.getLocalName().equals(identifier.getName())) {
588 if (identifier.getRevision().equals(qname.getRevision())) {
592 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
593 deviceSources.getRequiredSourcesQName());
594 // return null since we cannot find the QName,
595 // this capability will be removed from required sources and not reported as unresolved-capability