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 com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Predicates;
13 import com.google.common.collect.Collections2;
14 import com.google.common.collect.Lists;
15 import com.google.common.collect.Sets;
16 import com.google.common.util.concurrent.CheckedFuture;
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 java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.LinkedList;
26 import java.util.List;
28 import java.util.concurrent.Callable;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.ExecutorService;
31 import java.util.stream.Collectors;
32 import javax.annotation.Nonnull;
33 import javax.annotation.concurrent.GuardedBy;
34 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
35 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
36 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
37 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
38 import org.opendaylight.netconf.api.NetconfMessage;
39 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
40 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
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.NetconfRemoteSchemaYangSourceProvider;
50 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
51 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
52 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
53 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
54 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
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.yang.common.QName;
59 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
61 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
65 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
66 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
67 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
68 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
69 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
70 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
71 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
72 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
77 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
79 public class NetconfDevice
80 implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
82 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
84 protected final RemoteDeviceId id;
85 private final boolean reconnectOnSchemasChange;
87 protected final SchemaContextFactory schemaContextFactory;
88 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
89 private final ListeningExecutorService processingExecutor;
90 protected final SchemaSourceRegistry schemaRegistry;
91 protected final SchemaRepository schemaRepository;
92 private final NetconfDeviceSchemasResolver stateSchemasResolver;
93 private final NotificationHandler notificationHandler;
94 protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations =
97 private boolean connected = false;
99 // Message transformer is constructed once the schemas are available
100 private MessageTransformer<NetconfMessage> messageTransformer;
103 * Create rpc implementation capable of handling RPC for monitoring and notifications
104 * even before the schemas of remote device are downloaded.
106 static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener,
107 final boolean notificationSupport) {
108 final BaseSchema baseSchema = notificationSupport
109 ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS
110 : BaseSchema.BASE_NETCONF_CTX;
112 return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener,
113 new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
116 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
117 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
118 final ExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
120 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
121 this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
122 this.schemaRepository = schemaResourcesDTO.getSchemaRepository();
123 this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
124 this.salFacade = salFacade;
125 this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
126 this.processingExecutor = MoreExecutors.listeningDecorator(globalProcessingExecutor);
127 this.notificationHandler = new NotificationHandler(salFacade, id);
131 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
132 final NetconfDeviceCommunicator listener) {
133 // SchemaContext setup has to be performed in a dedicated thread since
134 // we are in a netty thread in this method
135 // Yang models are being downloaded in this method and it would cause a
136 // deadlock if we used the netty thread
137 // http://netty.io/wiki/thread-model.html
139 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
141 final NetconfDeviceRpc initRpc =
142 getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
143 final DeviceSourcesResolver task =
144 new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
145 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
147 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
148 registerToBaseNetconfStream(initRpc, listener);
151 final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
153 public void onSuccess(@Nonnull final DeviceSources result) {
154 addProvidedSourcesToSchemaRegistry(result);
158 private void setUpSchema(final DeviceSources result) {
159 processingExecutor.submit(new SchemaSetup(result, remoteSessionCapabilities, listener));
163 public void onFailure(final Throwable throwable) {
164 LOG.warn("{}: Unexpected error resolving device sources: {}", id, throwable);
165 handleSalInitializationFailure(throwable, listener);
169 Futures.addCallback(sourceResolverFuture, resolvedSourceCallback, MoreExecutors.directExecutor());
172 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
173 final NetconfDeviceCommunicator listener) {
174 // TODO check whether the model describing create subscription is present in schema
175 // Perhaps add a default schema context to support create-subscription if the model was not provided
176 // (same as what we do for base netconf operations in transformer)
177 final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultListenableFuture = deviceRpc.invokeRpc(
178 NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME),
179 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
181 final NotificationHandler.NotificationFilter filter = new NotificationHandler.NotificationFilter() {
183 public Optional<DOMNotification> filterNotification(final DOMNotification notification) {
184 if (isCapabilityChanged(notification)) {
185 LOG.info("{}: Schemas change detected, reconnecting", id);
186 // Only disconnect is enough,
187 // the reconnecting nature of the connector will take care of reconnecting
188 listener.disconnect();
189 return Optional.absent();
191 return Optional.of(notification);
194 private boolean isCapabilityChanged(final DOMNotification notification) {
195 return notification.getBody().getNodeType().equals(NetconfCapabilityChange.QNAME);
199 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
201 public void onSuccess(final DOMRpcResult domRpcResult) {
202 notificationHandler.addNotificationFilter(filter);
206 public void onFailure(final Throwable throwable) {
207 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
210 }, MoreExecutors.directExecutor());
213 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
214 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
217 private synchronized void handleSalInitializationSuccess(final SchemaContext result,
218 final NetconfSessionPreferences remoteSessionCapabilities,
219 final DOMRpcService deviceRpc) {
220 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
221 //since salFacade.onDeviceDisconnected was already called.
223 final BaseSchema baseSchema =
224 remoteSessionCapabilities.isNotificationsSupported()
225 ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
226 messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
228 updateTransformer(messageTransformer);
229 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
230 salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc);
231 notificationHandler.onRemoteSchemaUp(messageTransformer);
233 LOG.info("{}: Netconf connector initialized successfully", id);
235 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
239 private void handleSalInitializationFailure(final Throwable throwable,
240 final RemoteDeviceCommunicator<NetconfMessage> listener) {
241 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
243 onRemoteSessionDown();
244 resetMessageTransformer();
248 * Set the transformer to null as is in initial state.
250 private void resetMessageTransformer() {
251 updateTransformer(null);
254 private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
255 messageTransformer = transformer;
258 private synchronized void setConnected(final boolean connected) {
259 this.connected = connected;
262 private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
263 final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
264 for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
265 sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
266 PotentialSchemaSource.create(
267 sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
272 public void onRemoteSessionDown() {
274 notificationHandler.onRemoteSchemaDown();
276 salFacade.onDeviceDisconnected();
277 for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration
278 : sourceRegistrations) {
279 sourceRegistration.close();
281 resetMessageTransformer();
285 public void onRemoteSessionFailed(final Throwable throwable) {
287 salFacade.onDeviceFailed(throwable);
291 public void onNotification(final NetconfMessage notification) {
292 notificationHandler.handleNotification(notification);
296 * Just a transfer object containing schema related dependencies. Injected in constructor.
298 public static class SchemaResourcesDTO {
299 private final SchemaSourceRegistry schemaRegistry;
300 private final SchemaRepository schemaRepository;
301 private final SchemaContextFactory schemaContextFactory;
302 private final NetconfDeviceSchemasResolver stateSchemasResolver;
304 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
305 final SchemaRepository schemaRepository,
306 final SchemaContextFactory schemaContextFactory,
307 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
308 this.schemaRegistry = Preconditions.checkNotNull(schemaRegistry);
309 this.schemaRepository = Preconditions.checkNotNull(schemaRepository);
310 this.schemaContextFactory = Preconditions.checkNotNull(schemaContextFactory);
311 this.stateSchemasResolver = Preconditions.checkNotNull(deviceSchemasResolver);
314 public SchemaSourceRegistry getSchemaRegistry() {
315 return schemaRegistry;
318 public SchemaRepository getSchemaRepository() {
319 return schemaRepository;
322 public SchemaContextFactory getSchemaContextFactory() {
323 return schemaContextFactory;
326 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
327 return stateSchemasResolver;
332 * Schema building callable.
334 private static class DeviceSourcesResolver implements Callable<DeviceSources> {
336 private final NetconfDeviceRpc deviceRpc;
337 private final NetconfSessionPreferences remoteSessionCapabilities;
338 private final RemoteDeviceId id;
339 private final NetconfDeviceSchemasResolver stateSchemasResolver;
341 DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc,
342 final NetconfSessionPreferences remoteSessionCapabilities,
343 final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver) {
344 this.deviceRpc = deviceRpc;
345 this.remoteSessionCapabilities = remoteSessionCapabilities;
347 this.stateSchemasResolver = stateSchemasResolver;
350 DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
351 final NetconfDeviceSchemasResolver stateSchemasResolver,
352 final NetconfDeviceRpc rpcForMonitoring) {
353 this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver);
357 public DeviceSources call() throws Exception {
358 final NetconfDeviceSchemas availableSchemas =
359 stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
360 LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id,
361 availableSchemas.getAvailableYangSchemasQNames());
363 final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
364 final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
366 final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
367 if (!requiredSourcesNotProvided.isEmpty()) {
368 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities,"
369 + " required but not provided: {}", id, requiredSourcesNotProvided);
370 LOG.warn("{}: Attempting to build schema context from required sources", id);
373 // Here all the sources reported in netconf monitoring are merged with those reported in hello.
374 // It is necessary to perform this since submodules are not mentioned in hello but still required.
375 // This clashes with the option of a user to specify supported yang models manually in configuration
376 // for netconf-connector and as a result one is not able to fully override yang models of a device.
377 // It is only possible to add additional models.
378 final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
379 if (!providedSourcesNotRequired.isEmpty()) {
380 LOG.warn("{}: Netconf device provides additional yang models not reported in "
381 + "hello message capabilities: {}", id, providedSourcesNotRequired);
382 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
383 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
384 requiredSources.addAll(providedSourcesNotRequired);
387 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
388 if (availableSchemas instanceof LibraryModulesSchemas) {
389 sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
390 ((LibraryModulesSchemas) availableSchemas).getAvailableModels());
392 sourceProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
395 return new DeviceSources(requiredSources, providedSources, sourceProvider);
400 * Contains RequiredSources - sources from capabilities.
402 private static final class DeviceSources {
403 private final Set<QName> requiredSources;
404 private final Set<QName> providedSources;
405 private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
407 DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
408 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
409 this.requiredSources = requiredSources;
410 this.providedSources = providedSources;
411 this.sourceProvider = sourceProvider;
414 public Set<QName> getRequiredSourcesQName() {
415 return requiredSources;
418 public Set<QName> getProvidedSourcesQName() {
419 return providedSources;
422 public Collection<SourceIdentifier> getRequiredSources() {
423 return Collections2.transform(requiredSources, DeviceSources::toSourceId);
426 public Collection<SourceIdentifier> getProvidedSources() {
427 return Collections2.transform(providedSources, DeviceSources::toSourceId);
430 public SchemaSourceProvider<YangTextSchemaSource> getSourceProvider() {
431 return sourceProvider;
434 private static SourceIdentifier toSourceId(final QName input) {
435 return RevisionSourceIdentifier.create(input.getLocalName(), input.getRevision());
440 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
442 private final class SchemaSetup implements Runnable {
443 private final DeviceSources deviceSources;
444 private final NetconfSessionPreferences remoteSessionCapabilities;
445 private final RemoteDeviceCommunicator<NetconfMessage> listener;
446 private final NetconfDeviceCapabilities capabilities;
448 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities,
449 final RemoteDeviceCommunicator<NetconfMessage> listener) {
450 this.deviceSources = deviceSources;
451 this.remoteSessionCapabilities = remoteSessionCapabilities;
452 this.listener = listener;
453 this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
459 final Collection<SourceIdentifier> requiredSources = deviceSources.getRequiredSources();
460 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
462 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
463 UnavailableCapability.FailureReason.MissingSource);
465 requiredSources.removeAll(missingSources);
466 setUpSchema(requiredSources);
469 private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> requiredSources) {
470 return requiredSources.parallelStream().filter(sourceIdentifier -> {
472 schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).get();
474 } catch (InterruptedException | ExecutionException e) {
477 }).collect(Collectors.toList());
481 * Build schema context, in case of success or final failure notify device.
483 @SuppressWarnings("checkstyle:IllegalCatch")
484 private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
485 while (!requiredSources.isEmpty()) {
486 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
488 final ListenableFuture<SchemaContext> schemaBuilderFuture = schemaContextFactory
489 .createSchemaContext(requiredSources);
490 final SchemaContext result = schemaBuilderFuture.get();
491 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
492 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
493 capabilities.getUnresolvedCapabilites().keySet());
494 capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
495 .setCapability(entry.toString()).setCapabilityOrigin(
496 remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
497 .collect(Collectors.toList()));
499 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
500 .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
501 .setCapability(entry).setCapabilityOrigin(
502 remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
503 .collect(Collectors.toList()));
505 handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
507 } catch (final ExecutionException e) {
508 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
509 // that might be wrapping a MissingSchemaSourceException so we need to look
510 // at the cause of the exception to make sure we don't misinterpret it.
511 final Throwable cause = e.getCause();
513 if (cause instanceof MissingSchemaSourceException) {
514 requiredSources = handleMissingSchemaSourceException(
515 requiredSources, (MissingSchemaSourceException) cause);
518 if (cause instanceof SchemaResolutionException) {
519 requiredSources = handleSchemaResolutionException(requiredSources,
520 (SchemaResolutionException) cause);
522 handleSalInitializationFailure(e, listener);
525 } catch (final Exception e) {
526 // unknown error, fail
527 handleSalInitializationFailure(e, listener);
531 // No more sources, fail
532 final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context");
533 handleSalInitializationFailure(cause, listener);
534 salFacade.onDeviceFailed(cause);
537 private Collection<SourceIdentifier> handleMissingSchemaSourceException(
538 final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException exception) {
539 // In case source missing, try without it
540 final SourceIdentifier missingSource = exception.getSourceId();
541 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id,
543 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
545 final Collection<QName> qNameOfMissingSource =
546 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
547 if (!qNameOfMissingSource.isEmpty()) {
548 capabilities.addUnresolvedCapabilities(
549 qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
551 return stripUnavailableSource(requiredSources, missingSource);
554 private Collection<SourceIdentifier> handleSchemaResolutionException(
555 final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
556 // In case resolution error, try only with resolved sources
557 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
558 // FIXME Do we really have assurance that these two cases cannot happen at once?
559 if (resolutionException.getFailedSource() != null) {
560 // flawed model - exclude it
561 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
562 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
564 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
565 id, resolutionException);
566 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(
567 Collections.singleton(failedSourceId)), UnavailableCapability.FailureReason.UnableToResolve);
568 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
570 // unsatisfied imports
571 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
572 capabilities.addUnresolvedCapabilities(
573 getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
574 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
575 id, resolutionException.getUnsatisfiedImports());
576 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
577 resolutionException);
578 return resolutionException.getResolvedSources();
581 protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
582 return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
585 private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources,
586 final SourceIdentifier sourceIdToRemove) {
587 final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
588 final boolean removed = sourceIdentifiers.remove(sourceIdToRemove);
589 Preconditions.checkState(
590 removed, "{}: Trying to remove {} from {} 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.getName())) {
611 if (identifier.getRevision().equals(qname.getRevision())) {
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