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 io.netty.util.concurrent.EventExecutor;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.Objects;
31 import java.util.Optional;
33 import java.util.concurrent.ExecutionException;
34 import java.util.concurrent.TimeUnit;
35 import java.util.stream.Collectors;
36 import org.checkerframework.checker.lock.qual.GuardedBy;
37 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
38 import org.opendaylight.mdsal.dom.api.DOMRpcService;
39 import org.opendaylight.netconf.api.NetconfMessage;
40 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
41 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
42 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
43 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
44 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
45 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
46 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
47 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
50 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
51 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseNetconfSchemas;
52 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
53 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
54 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
55 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.optional.rev190614.NetconfNodeAugmentedOptional;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
61 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
62 import org.opendaylight.yangtools.rfc8528.data.util.EmptyMountPointContext;
63 import org.opendaylight.yangtools.rfc8528.model.api.SchemaMountConstants;
64 import org.opendaylight.yangtools.yang.common.QName;
65 import org.opendaylight.yangtools.yang.common.RpcError;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
70 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
71 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
72 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
73 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
74 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
75 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
76 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
77 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
78 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
79 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
80 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
81 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
86 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
88 public class NetconfDevice
89 implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
90 private 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 BaseNetconfSchemas baseSchemas;
111 private final NetconfNode node;
112 private final EventExecutor eventExecutor;
113 private final NetconfNodeAugmentedOptional nodeOptional;
116 private boolean connected = false;
118 // Message transformer is constructed once the schemas are available
119 private MessageTransformer<NetconfMessage> messageTransformer;
121 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final BaseNetconfSchemas baseSchemas,
122 final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
123 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
124 this(schemaResourcesDTO, baseSchemas, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null,
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 final DeviceActionFactory deviceActionFactory, final NetconfNode node, final EventExecutor eventExecutor,
132 final NetconfNodeAugmentedOptional nodeOptional) {
133 this.baseSchemas = requireNonNull(baseSchemas);
135 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
136 this.deviceActionFactory = deviceActionFactory;
138 this.eventExecutor = eventExecutor;
139 this.nodeOptional = nodeOptional;
140 schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
141 schemaRepository = schemaResourcesDTO.getSchemaRepository();
142 schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
143 this.salFacade = salFacade;
144 stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
145 processingExecutor = requireNonNull(globalProcessingExecutor);
146 notificationHandler = new NotificationHandler(salFacade, id);
150 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
151 final NetconfDeviceCommunicator listener) {
152 // SchemaContext setup has to be performed in a dedicated thread since
153 // we are in a netty thread in this method
154 // Yang models are being downloaded in this method and it would cause a
155 // deadlock if we used the netty thread
156 // http://netty.io/wiki/thread-model.html
158 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
160 final BaseSchema baseSchema = resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported());
161 final NetconfDeviceRpc initRpc = new NetconfDeviceRpc(baseSchema.getEffectiveModelContext(), listener,
162 new NetconfMessageTransformer(baseSchema.getMountPointContext(), false, baseSchema));
163 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(
164 new DeviceSourcesResolver(id, baseSchema, initRpc, remoteSessionCapabilities, stateSchemasResolver));
166 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
167 registerToBaseNetconfStream(initRpc, listener);
170 // Set up the SchemaContext for the device
171 final ListenableFuture<EffectiveModelContext> futureSchema = Futures.transformAsync(sourceResolverFuture,
172 deviceSources -> assembleSchemaContext(deviceSources, remoteSessionCapabilities), processingExecutor);
174 // Potentially acquire mount point list and interpret it
175 final ListenableFuture<MountPointContext> futureContext = Futures.transformAsync(futureSchema,
176 schemaContext -> createMountPointContext(schemaContext, baseSchema, listener), processingExecutor);
178 Futures.addCallback(futureContext, new FutureCallback<MountPointContext>() {
180 public void onSuccess(final MountPointContext result) {
181 handleSalInitializationSuccess(result, remoteSessionCapabilities,
182 getDeviceSpecificRpc(result, listener, baseSchema), listener);
186 public void onFailure(final Throwable cause) {
187 LOG.warn("{}: Unexpected error resolving device sources", id, cause);
189 // No more sources, fail or try to reconnect
190 if (cause instanceof EmptySchemaContextException) {
191 if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().getAllowed()) {
192 eventExecutor.schedule(() -> {
193 LOG.warn("Reconnection is allowed! This can lead to unexpected errors at runtime.");
194 LOG.warn("{} : No more sources for schema context.", id);
195 LOG.info("{} : Try to remount device.", id);
196 onRemoteSessionDown();
197 salFacade.onDeviceReconnected(remoteSessionCapabilities, node);
198 }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime().toJava(),
199 TimeUnit.MILLISECONDS);
204 handleSalInitializationFailure(cause, listener);
205 salFacade.onDeviceFailed(cause);
207 }, MoreExecutors.directExecutor());
210 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
211 final NetconfDeviceCommunicator listener) {
212 // TODO check whether the model describing create subscription is present in schema
213 // Perhaps add a default schema context to support create-subscription if the model was not provided
214 // (same as what we do for base netconf operations in transformer)
215 final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
216 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME,
217 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
219 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
221 public void onSuccess(final DOMRpcResult domRpcResult) {
222 notificationHandler.addNotificationFilter(notification -> {
223 if (NetconfCapabilityChange.QNAME.equals(notification.getBody().getIdentifier().getNodeType())) {
224 LOG.info("{}: Schemas change detected, reconnecting", id);
225 // Only disconnect is enough,
226 // the reconnecting nature of the connector will take care of reconnecting
227 listener.disconnect();
228 return Optional.empty();
230 return Optional.of(notification);
235 public void onFailure(final Throwable throwable) {
236 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
239 }, MoreExecutors.directExecutor());
242 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
243 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
246 private synchronized void handleSalInitializationSuccess(final MountPointContext result,
247 final NetconfSessionPreferences remoteSessionCapabilities,
248 final DOMRpcService deviceRpc,
249 final RemoteDeviceCommunicator<NetconfMessage> listener) {
250 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
251 //since salFacade.onDeviceDisconnected was already called.
253 messageTransformer = new NetconfMessageTransformer(result, true,
254 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()));
256 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
257 salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
258 deviceActionFactory == null ? null : deviceActionFactory.createDeviceAction(
259 messageTransformer, listener, result.getEffectiveModelContext()));
260 notificationHandler.onRemoteSchemaUp(messageTransformer);
262 LOG.info("{}: Netconf connector initialized successfully", id);
264 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
268 private void handleSalInitializationFailure(final Throwable throwable,
269 final RemoteDeviceCommunicator<NetconfMessage> listener) {
270 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
272 onRemoteSessionDown();
273 resetMessageTransformer();
277 * Set the transformer to null as is in initial state.
279 private void resetMessageTransformer() {
280 updateTransformer(null);
283 private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
284 messageTransformer = transformer;
287 private synchronized void setConnected(final boolean connected) {
288 this.connected = connected;
291 private ListenableFuture<EffectiveModelContext> assembleSchemaContext(final DeviceSources deviceSources,
292 final NetconfSessionPreferences remoteSessionCapabilities) {
293 LOG.debug("{}: Resolved device sources to {}", id, deviceSources);
294 final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
295 for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
296 sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
297 PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class,
298 PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
301 return new SchemaSetup(deviceSources, remoteSessionCapabilities).startResolution();
304 private ListenableFuture<MountPointContext> createMountPointContext(final EffectiveModelContext schemaContext,
305 final BaseSchema baseSchema, final NetconfDeviceCommunicator listener) {
306 final MountPointContext emptyContext = new EmptyMountPointContext(schemaContext);
307 if (schemaContext.findModule(SchemaMountConstants.RFC8528_MODULE).isEmpty()) {
308 return Futures.immediateFuture(emptyContext);
311 // Create a temporary RPC invoker and acquire the mount point tree
312 LOG.debug("{}: Acquiring available mount points", id);
313 final NetconfDeviceRpc deviceRpc = new NetconfDeviceRpc(schemaContext, listener,
314 new NetconfMessageTransformer(emptyContext, false, baseSchema));
316 return Futures.transform(deviceRpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_GET_QNAME,
317 Builders.containerBuilder().withNodeIdentifier(NETCONF_GET_NODEID)
318 .withChild(NetconfMessageTransformUtil.toFilterStructure(RFC8528_SCHEMA_MOUNTS, schemaContext))
319 .build()), rpcResult -> processSchemaMounts(rpcResult, emptyContext), MoreExecutors.directExecutor());
322 private MountPointContext processSchemaMounts(final DOMRpcResult rpcResult, final MountPointContext emptyContext) {
323 final Collection<? extends RpcError> errors = rpcResult.getErrors();
324 if (!errors.isEmpty()) {
325 LOG.warn("{}: Schema-mounts acquisition resulted in errors {}", id, errors);
327 final NormalizedNode schemaMounts = rpcResult.getResult();
328 if (schemaMounts == null) {
329 LOG.debug("{}: device does not define any schema mounts", id);
332 if (!(schemaMounts instanceof ContainerNode)) {
333 LOG.warn("{}: ignoring non-container schema mounts {}", id, schemaMounts);
337 return DeviceMountPointContext.create(emptyContext, (ContainerNode) schemaMounts);
341 public void onRemoteSessionDown() {
343 notificationHandler.onRemoteSchemaDown();
345 salFacade.onDeviceDisconnected();
346 sourceRegistrations.forEach(SchemaSourceRegistration::close);
347 sourceRegistrations.clear();
348 resetMessageTransformer();
352 public void onRemoteSessionFailed(final Throwable throwable) {
354 salFacade.onDeviceFailed(throwable);
358 public void onNotification(final NetconfMessage notification) {
359 notificationHandler.handleNotification(notification);
362 private BaseSchema resolveBaseSchema(final boolean notificationSupport) {
363 return notificationSupport ? baseSchemas.getBaseSchemaWithNotifications() : baseSchemas.getBaseSchema();
366 protected NetconfDeviceRpc getDeviceSpecificRpc(final MountPointContext result,
367 final RemoteDeviceCommunicator<NetconfMessage> listener, final BaseSchema schema) {
368 return new NetconfDeviceRpc(result.getEffectiveModelContext(), listener,
369 new NetconfMessageTransformer(result, true, schema));
373 * Just a transfer object containing schema related dependencies. Injected in constructor.
375 public static class SchemaResourcesDTO {
376 private final SchemaSourceRegistry schemaRegistry;
377 private final SchemaRepository schemaRepository;
378 private final EffectiveModelContextFactory schemaContextFactory;
379 private final NetconfDeviceSchemasResolver stateSchemasResolver;
381 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
382 final SchemaRepository schemaRepository,
383 final EffectiveModelContextFactory schemaContextFactory,
384 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
385 this.schemaRegistry = requireNonNull(schemaRegistry);
386 this.schemaRepository = requireNonNull(schemaRepository);
387 this.schemaContextFactory = requireNonNull(schemaContextFactory);
388 stateSchemasResolver = requireNonNull(deviceSchemasResolver);
391 public SchemaSourceRegistry getSchemaRegistry() {
392 return schemaRegistry;
395 public SchemaRepository getSchemaRepository() {
396 return schemaRepository;
399 public EffectiveModelContextFactory getSchemaContextFactory() {
400 return schemaContextFactory;
403 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
404 return stateSchemasResolver;
409 * A dedicated exception to indicate when we fail to setup a SchemaContext.
411 * @author Robert Varga
413 private static final class EmptySchemaContextException extends Exception {
414 private static final long serialVersionUID = 1L;
416 EmptySchemaContextException(final String message) {
422 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
424 private final class SchemaSetup implements FutureCallback<EffectiveModelContext> {
425 private final SettableFuture<EffectiveModelContext> resultFuture = SettableFuture.create();
427 private final DeviceSources deviceSources;
428 private final NetconfSessionPreferences remoteSessionCapabilities;
429 private final NetconfDeviceCapabilities capabilities;
431 private Collection<SourceIdentifier> requiredSources;
433 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities) {
434 this.deviceSources = deviceSources;
435 this.remoteSessionCapabilities = remoteSessionCapabilities;
436 capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
438 // If device supports notifications and does not contain necessary modules, add them automatically
439 if (remoteSessionCapabilities.containsNonModuleCapability(
440 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0)) {
441 deviceSources.getRequiredSourcesQName().addAll(
443 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
444 .$YangModuleInfoImpl.getInstance().getName(),
445 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
446 .$YangModuleInfoImpl.getInstance().getName()
451 requiredSources = deviceSources.getRequiredSources();
452 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
454 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
455 UnavailableCapability.FailureReason.MissingSource);
456 requiredSources.removeAll(missingSources);
459 ListenableFuture<EffectiveModelContext> startResolution() {
465 public void onSuccess(final EffectiveModelContext result) {
466 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
468 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
469 capabilities.getUnresolvedCapabilites().keySet());
470 capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
471 .setCapability(entry.toString()).setCapabilityOrigin(
472 remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
473 .collect(Collectors.toList()));
475 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
476 .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
477 .setCapability(entry).setCapabilityOrigin(
478 remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
479 .collect(Collectors.toList()));
481 resultFuture.set(result);
485 public void onFailure(final Throwable cause) {
486 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
487 // that might be wrapping a MissingSchemaSourceException so we need to look
488 // at the cause of the exception to make sure we don't misinterpret it.
489 if (cause instanceof MissingSchemaSourceException) {
490 requiredSources = handleMissingSchemaSourceException((MissingSchemaSourceException) cause);
491 } else if (cause instanceof SchemaResolutionException) {
492 requiredSources = handleSchemaResolutionException((SchemaResolutionException) cause);
494 LOG.debug("Unhandled failure", cause);
495 resultFuture.setException(cause);
503 private void trySetupSchema() {
504 if (!requiredSources.isEmpty()) {
505 // Initiate async resolution, drive it back based on the result
506 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
507 Futures.addCallback(schemaContextFactory.createEffectiveModelContext(requiredSources), this,
508 MoreExecutors.directExecutor());
510 LOG.debug("{}: no more sources for schema context", id);
511 resultFuture.setException(new EmptySchemaContextException(id + ": No more sources for schema context"));
515 private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> origSources) {
516 return origSources.parallelStream().filter(sourceIdentifier -> {
518 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
520 } catch (InterruptedException | ExecutionException e) {
523 }).collect(Collectors.toList());
526 private Collection<SourceIdentifier> handleMissingSchemaSourceException(
527 final MissingSchemaSourceException exception) {
528 // In case source missing, try without it
529 final SourceIdentifier missingSource = exception.getSourceId();
530 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
532 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
533 id, missingSource, exception);
534 final Collection<QName> qNameOfMissingSource =
535 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
536 if (!qNameOfMissingSource.isEmpty()) {
537 capabilities.addUnresolvedCapabilities(
538 qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
540 return stripUnavailableSource(missingSource);
543 private Collection<SourceIdentifier> handleSchemaResolutionException(
544 final SchemaResolutionException resolutionException) {
545 // In case resolution error, try only with resolved sources
546 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
547 // FIXME Do we really have assurance that these two cases cannot happen at once?
548 if (resolutionException.getFailedSource() != null) {
549 // flawed model - exclude it
550 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
551 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
553 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
554 id, failedSourceId, resolutionException);
555 capabilities.addUnresolvedCapabilities(
556 getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
557 UnavailableCapability.FailureReason.UnableToResolve);
558 return stripUnavailableSource(resolutionException.getFailedSource());
560 // unsatisfied imports
561 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
562 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
563 UnavailableCapability.FailureReason.UnableToResolve);
564 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
565 id, resolutionException.getUnsatisfiedImports());
566 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
567 id, resolutionException.getUnsatisfiedImports(), resolutionException);
568 return resolutionException.getResolvedSources();
571 private Collection<SourceIdentifier> stripUnavailableSource(final SourceIdentifier sourceIdToRemove) {
572 final LinkedList<SourceIdentifier> sourceIdentifiers = new LinkedList<>(requiredSources);
573 checkState(sourceIdentifiers.remove(sourceIdToRemove),
574 "%s: Trying to remove %s from %s failed", id, sourceIdToRemove, requiredSources);
575 return sourceIdentifiers;
578 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
579 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
581 if (qNames.isEmpty()) {
582 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
585 return Collections2.filter(qNames, Predicates.notNull());
588 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
589 // Required sources are all required and provided merged in DeviceSourcesResolver
590 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
591 if (!qname.getLocalName().equals(identifier.name().getLocalName())) {
595 if (Objects.equals(identifier.revision(), qname.getRevision().orElse(null))) {
599 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
600 deviceSources.getRequiredSourcesQName());
601 // return null since we cannot find the QName,
602 // this capability will be removed from required sources and not reported as unresolved-capability