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.ExecutorService;
30 import java.util.stream.Collectors;
31 import javax.annotation.concurrent.GuardedBy;
32 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
33 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
34 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
35 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
36 import org.opendaylight.netconf.api.NetconfMessage;
37 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
38 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
39 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
40 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
41 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
42 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
43 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
44 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
45 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
46 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
47 import org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
48 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
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.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
58 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
59 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
60 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
61 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
65 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
66 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
67 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
68 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
69 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
70 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
71 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
76 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
78 public class NetconfDevice
79 implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
81 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
83 protected final RemoteDeviceId id;
84 private final boolean reconnectOnSchemasChange;
86 protected final SchemaContextFactory schemaContextFactory;
87 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
88 private final ListeningExecutorService processingExecutor;
89 protected final SchemaSourceRegistry schemaRegistry;
90 protected final SchemaRepository schemaRepository;
91 private final NetconfDeviceSchemasResolver stateSchemasResolver;
92 private final NotificationHandler notificationHandler;
93 protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations =
96 private boolean connected = false;
98 // Message transformer is constructed once the schemas are available
99 private MessageTransformer<NetconfMessage> messageTransformer;
102 * Create rpc implementation capable of handling RPC for monitoring and notifications
103 * even before the schemas of remote device are downloaded.
105 static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener,
106 final boolean notificationSupport) {
107 final BaseSchema baseSchema = notificationSupport
108 ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS
109 : BaseSchema.BASE_NETCONF_CTX;
111 return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener,
112 new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
115 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
116 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
117 final ExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
119 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
120 this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
121 this.schemaRepository = schemaResourcesDTO.getSchemaRepository();
122 this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
123 this.salFacade = salFacade;
124 this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
125 this.processingExecutor = MoreExecutors.listeningDecorator(globalProcessingExecutor);
126 this.notificationHandler = new NotificationHandler(salFacade, id);
130 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
131 final NetconfDeviceCommunicator listener) {
132 // SchemaContext setup has to be performed in a dedicated thread since
133 // we are in a netty thread in this method
134 // Yang models are being downloaded in this method and it would cause a
135 // deadlock if we used the netty thread
136 // http://netty.io/wiki/thread-model.html
138 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
140 final NetconfDeviceRpc initRpc =
141 getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
142 final DeviceSourcesResolver task =
143 new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
144 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
146 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
147 registerToBaseNetconfStream(initRpc, listener);
150 final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
152 public void onSuccess(final DeviceSources result) {
153 addProvidedSourcesToSchemaRegistry(result);
157 private void setUpSchema(final DeviceSources result) {
158 processingExecutor.submit(new SchemaSetup(result, remoteSessionCapabilities, listener));
162 public void onFailure(final Throwable throwable) {
163 LOG.warn("{}: Unexpected error resolving device sources: {}", id, throwable);
164 handleSalInitializationFailure(throwable, listener);
168 Futures.addCallback(sourceResolverFuture, resolvedSourceCallback);
171 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
172 final NetconfDeviceCommunicator listener) {
173 // TODO check whether the model describing create subscription is present in schema
174 // Perhaps add a default schema context to support create-subscription if the model was not provided
175 // (same as what we do for base netconf operations in transformer)
176 final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultListenableFuture = deviceRpc.invokeRpc(
177 NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME),
178 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
180 final NotificationHandler.NotificationFilter filter = new NotificationHandler.NotificationFilter() {
182 public Optional<DOMNotification> filterNotification(final DOMNotification notification) {
183 if (isCapabilityChanged(notification)) {
184 LOG.info("{}: Schemas change detected, reconnecting", id);
185 // Only disconnect is enough,
186 // the reconnecting nature of the connector will take care of reconnecting
187 listener.disconnect();
188 return Optional.absent();
190 return Optional.of(notification);
193 private boolean isCapabilityChanged(final DOMNotification notification) {
194 return notification.getBody().getNodeType().equals(NetconfCapabilityChange.QNAME);
198 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
200 public void onSuccess(final DOMRpcResult domRpcResult) {
201 notificationHandler.addNotificationFilter(filter);
205 public void onFailure(final Throwable throwable) {
206 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
212 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
213 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
216 private synchronized void handleSalInitializationSuccess(final SchemaContext result,
217 final NetconfSessionPreferences remoteSessionCapabilities,
218 final DOMRpcService deviceRpc) {
219 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
220 //since salFacade.onDeviceDisconnected was already called.
222 final BaseSchema baseSchema =
223 remoteSessionCapabilities.isNotificationsSupported()
224 ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
225 messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
227 updateTransformer(messageTransformer);
228 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
229 salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc);
230 notificationHandler.onRemoteSchemaUp(messageTransformer);
232 LOG.info("{}: Netconf connector initialized successfully", id);
234 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
238 private void handleSalInitializationFailure(final Throwable throwable,
239 final RemoteDeviceCommunicator<NetconfMessage> listener) {
240 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
242 onRemoteSessionDown();
243 resetMessageTransformer();
247 * Set the transformer to null as is in initial state.
249 private void resetMessageTransformer() {
250 updateTransformer(null);
253 private void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
254 messageTransformer = transformer;
257 private synchronized void setConnected(final boolean connected) {
258 this.connected = connected;
261 private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
262 final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
263 for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
264 sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
265 PotentialSchemaSource.create(
266 sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
271 public void onRemoteSessionDown() {
273 notificationHandler.onRemoteSchemaDown();
275 salFacade.onDeviceDisconnected();
276 for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration
277 : sourceRegistrations) {
278 sourceRegistration.close();
280 resetMessageTransformer();
284 public void onRemoteSessionFailed(final Throwable throwable) {
286 salFacade.onDeviceFailed(throwable);
290 public void onNotification(final NetconfMessage notification) {
291 notificationHandler.handleNotification(notification);
295 * Just a transfer object containing schema related dependencies. Injected in constructor.
297 public static class SchemaResourcesDTO {
298 private final SchemaSourceRegistry schemaRegistry;
299 private final SchemaRepository schemaRepository;
300 private final SchemaContextFactory schemaContextFactory;
301 private final NetconfDeviceSchemasResolver stateSchemasResolver;
303 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
304 final SchemaRepository schemaRepository,
305 final SchemaContextFactory schemaContextFactory,
306 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
307 this.schemaRegistry = Preconditions.checkNotNull(schemaRegistry);
308 this.schemaRepository = Preconditions.checkNotNull(schemaRepository);
309 this.schemaContextFactory = Preconditions.checkNotNull(schemaContextFactory);
310 this.stateSchemasResolver = Preconditions.checkNotNull(deviceSchemasResolver);
313 public SchemaSourceRegistry getSchemaRegistry() {
314 return schemaRegistry;
317 public SchemaRepository getSchemaRepository() {
318 return schemaRepository;
321 public SchemaContextFactory getSchemaContextFactory() {
322 return schemaContextFactory;
325 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
326 return stateSchemasResolver;
331 * Schema building callable.
333 private static class DeviceSourcesResolver implements Callable<DeviceSources> {
335 private final NetconfDeviceRpc deviceRpc;
336 private final NetconfSessionPreferences remoteSessionCapabilities;
337 private final RemoteDeviceId id;
338 private final NetconfDeviceSchemasResolver stateSchemasResolver;
340 DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc,
341 final NetconfSessionPreferences remoteSessionCapabilities,
342 final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver) {
343 this.deviceRpc = deviceRpc;
344 this.remoteSessionCapabilities = remoteSessionCapabilities;
346 this.stateSchemasResolver = stateSchemasResolver;
349 DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
350 final NetconfDeviceSchemasResolver stateSchemasResolver,
351 final NetconfDeviceRpc rpcForMonitoring) {
352 this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver);
356 public DeviceSources call() throws Exception {
357 final NetconfDeviceSchemas availableSchemas =
358 stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
359 LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id,
360 availableSchemas.getAvailableYangSchemasQNames());
362 final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
363 final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
365 final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
366 if (!requiredSourcesNotProvided.isEmpty()) {
367 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities,"
368 + " required but not provided: {}", id, requiredSourcesNotProvided);
369 LOG.warn("{}: Attempting to build schema context from required sources", id);
372 // Here all the sources reported in netconf monitoring are merged with those reported in hello.
373 // It is necessary to perform this since submodules are not mentioned in hello but still required.
374 // This clashes with the option of a user to specify supported yang models manually in configuration
375 // for netconf-connector and as a result one is not able to fully override yang models of a device.
376 // It is only possible to add additional models.
377 final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
378 if (!providedSourcesNotRequired.isEmpty()) {
379 LOG.warn("{}: Netconf device provides additional yang models not reported in "
380 + "hello message capabilities: {}", id, providedSourcesNotRequired);
381 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
382 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
383 requiredSources.addAll(providedSourcesNotRequired);
386 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
387 if (availableSchemas instanceof LibraryModulesSchemas) {
388 sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
389 ((LibraryModulesSchemas) availableSchemas).getAvailableModels());
391 sourceProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
394 return new DeviceSources(requiredSources, providedSources, sourceProvider);
399 * Contains RequiredSources - sources from capabilities.
401 private static final class DeviceSources {
402 private final Set<QName> requiredSources;
403 private final Set<QName> providedSources;
404 private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
406 DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
407 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
408 this.requiredSources = requiredSources;
409 this.providedSources = providedSources;
410 this.sourceProvider = sourceProvider;
413 public Set<QName> getRequiredSourcesQName() {
414 return requiredSources;
417 public Set<QName> getProvidedSourcesQName() {
418 return providedSources;
421 public Collection<SourceIdentifier> getRequiredSources() {
422 return Collections2.transform(requiredSources, DeviceSources::toSourceId);
425 public Collection<SourceIdentifier> getProvidedSources() {
426 return Collections2.transform(providedSources, DeviceSources::toSourceId);
429 public SchemaSourceProvider<YangTextSchemaSource> getSourceProvider() {
430 return sourceProvider;
433 private static SourceIdentifier toSourceId(final QName input) {
434 return RevisionSourceIdentifier.create(input.getLocalName(),
435 Optional.fromNullable(input.getFormattedRevision()));
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) {
471 return requiredSources.parallelStream().filter(sourceIdentifier -> {
472 boolean remove = false;
474 schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).checkedGet();
475 } catch (SchemaSourceException e) {
479 }).collect(Collectors.toList());
483 * Build schema context, in case of success or final failure notify device.
485 @SuppressWarnings("checkstyle:IllegalCatch")
486 private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
487 while (!requiredSources.isEmpty()) {
488 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
490 final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture =
491 schemaContextFactory.createSchemaContext(requiredSources);
492 final SchemaContext result = schemaBuilderFuture.checkedGet();
493 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
494 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
495 capabilities.getUnresolvedCapabilites().keySet());
496 capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
497 .setCapability(entry.toString()).setCapabilityOrigin(
498 remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
499 .collect(Collectors.toList()));
501 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
502 .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
503 .setCapability(entry).setCapabilityOrigin(
504 remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
505 .collect(Collectors.toList()));
507 handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
509 } catch (final SchemaResolutionException e) {
510 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
511 // that might be wrapping a MissingSchemaSourceException so we need to look
512 // at the cause of the exception to make sure we don't misinterpret it.
513 if (e.getCause() instanceof MissingSchemaSourceException) {
514 requiredSources = handleMissingSchemaSourceException(
515 requiredSources, (MissingSchemaSourceException) e.getCause());
518 requiredSources = handleSchemaResolutionException(requiredSources, e);
519 } catch (final Exception e) {
520 // unknown error, fail
521 handleSalInitializationFailure(e, listener);
525 // No more sources, fail
526 final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context");
527 handleSalInitializationFailure(cause, listener);
528 salFacade.onDeviceFailed(cause);
531 private Collection<SourceIdentifier> handleMissingSchemaSourceException(
532 final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException exception) {
533 // In case source missing, try without it
534 final SourceIdentifier missingSource = exception.getSourceId();
535 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id,
537 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
539 final Collection<QName> qNameOfMissingSource =
540 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
541 if (!qNameOfMissingSource.isEmpty()) {
542 capabilities.addUnresolvedCapabilities(
543 qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
545 return stripUnavailableSource(requiredSources, missingSource);
548 private Collection<SourceIdentifier> handleSchemaResolutionException(
549 final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
550 // In case resolution error, try only with resolved sources
551 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
552 // FIXME Do we really have assurance that these two cases cannot happen at once?
553 if (resolutionException.getFailedSource() != null) {
554 // flawed model - exclude it
555 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
556 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
558 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
559 id, resolutionException);
560 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(
561 Collections.singleton(failedSourceId)), UnavailableCapability.FailureReason.UnableToResolve);
562 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
564 // unsatisfied imports
565 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
566 capabilities.addUnresolvedCapabilities(
567 getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
568 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
569 id, resolutionException.getUnsatisfiedImports());
570 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
571 resolutionException);
572 return resolutionException.getResolvedSources();
575 protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
576 return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
579 private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources,
580 final SourceIdentifier sourceIdToRemove) {
581 final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
582 final boolean removed = sourceIdentifiers.remove(sourceIdToRemove);
583 Preconditions.checkState(
584 removed, "{}: Trying to remove {} from {} failed", id, sourceIdToRemove, requiredSources);
585 return sourceIdentifiers;
588 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
589 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
591 if (qNames.isEmpty()) {
592 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
595 return Collections2.filter(qNames, Predicates.notNull());
598 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
599 // Required sources are all required and provided merged in DeviceSourcesResolver
600 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
601 if (!qname.getLocalName().equals(identifier.getName())) {
605 final String rev = getNullableRev(identifier);
607 if (qname.getRevision() == null) {
610 } else if (qname.getFormattedRevision().equals(rev)) {
614 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
615 deviceSources.getRequiredSourcesQName());
616 // return null since we cannot find the QName,
617 // this capability will be removed from required sources and not reported as unresolved-capability
621 private String getNullableRev(final SourceIdentifier identifier) {
622 final String rev = identifier.getRevision();
623 return rev == null || SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(rev) ? null : rev;