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.Function;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicates;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Sets;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.FutureCallback;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.ListeningExecutorService;
22 import com.google.common.util.concurrent.MoreExecutors;
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 org.opendaylight.controller.md.sal.dom.api.DOMNotification;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
33 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
34 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
35 import org.opendaylight.netconf.api.NetconfMessage;
36 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
37 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
38 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
39 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
40 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
41 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
42 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
43 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
44 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
45 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
46 import org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
47 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
48 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
49 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
50 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
51 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
57 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
58 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
59 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
60 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
61 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
63 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
65 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
66 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
67 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
68 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
69 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
74 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
76 public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
78 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
80 public static final Function<QName, SourceIdentifier> QNAME_TO_SOURCE_ID_FUNCTION = new Function<QName, SourceIdentifier>() {
82 public SourceIdentifier apply(final QName input) {
83 return RevisionSourceIdentifier
84 .create(input.getLocalName(), Optional.fromNullable(input.getFormattedRevision()));
88 protected final RemoteDeviceId id;
89 private final boolean reconnectOnSchemasChange;
91 protected final SchemaContextFactory schemaContextFactory;
92 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
93 private final ListeningExecutorService processingExecutor;
94 protected final SchemaSourceRegistry schemaRegistry;
95 protected final SchemaRepository schemaRepository;
96 private final NetconfDeviceSchemasResolver stateSchemasResolver;
97 private final NotificationHandler notificationHandler;
98 protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations = Lists.newArrayList();
100 // Message transformer is constructed once the schemas are available
101 private MessageTransformer<NetconfMessage> messageTransformer;
104 * Create rpc implementation capable of handling RPC for monitoring and notifications even before the schemas of remote device are downloaded
106 static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, 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, new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
114 protected NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
115 final ExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
117 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
118 this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
119 this.schemaRepository = schemaResourcesDTO.getSchemaRepository();
120 this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
121 this.salFacade = salFacade;
122 this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
123 this.processingExecutor = MoreExecutors.listeningDecorator(globalProcessingExecutor);
124 this.notificationHandler = new NotificationHandler(salFacade, id);
128 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
129 final NetconfDeviceCommunicator listener) {
130 // SchemaContext setup has to be performed in a dedicated thread since
131 // we are in a netty thread in this method
132 // Yang models are being downloaded in this method and it would cause a
133 // deadlock if we used the netty thread
134 // http://netty.io/wiki/thread-model.html
135 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
137 final NetconfDeviceRpc initRpc = getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
138 final DeviceSourcesResolver task = new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
139 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
141 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
142 registerToBaseNetconfStream(initRpc, listener);
145 final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
147 public void onSuccess(final DeviceSources result) {
148 addProvidedSourcesToSchemaRegistry(result);
152 private void setUpSchema(final DeviceSources result) {
153 processingExecutor.submit(new SchemaSetup(result, remoteSessionCapabilities, listener));
157 public void onFailure(final Throwable t) {
158 LOG.warn("{}: Unexpected error resolving device sources: {}", id, t);
159 handleSalInitializationFailure(t, listener);
163 Futures.addCallback(sourceResolverFuture, resolvedSourceCallback);
166 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc, final NetconfDeviceCommunicator listener) {
167 // TODO check whether the model describing create subscription is present in schema
168 // Perhaps add a default schema context to support create-subscription if the model was not provided (same as what we do for base netconf operations in transformer)
169 final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultListenableFuture =
170 deviceRpc.invokeRpc(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME), NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
172 final NotificationHandler.NotificationFilter filter = new NotificationHandler.NotificationFilter() {
174 public Optional<DOMNotification> filterNotification(final DOMNotification notification) {
175 if (isCapabilityChanged(notification)) {
176 LOG.info("{}: Schemas change detected, reconnecting", id);
177 // Only disconnect is enough, the reconnecting nature of the connector will take care of reconnecting
178 listener.disconnect();
179 return Optional.absent();
181 return Optional.of(notification);
184 private boolean isCapabilityChanged(final DOMNotification notification) {
185 return notification.getBody().getNodeType().equals(NetconfCapabilityChange.QNAME);
189 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
191 public void onSuccess(final DOMRpcResult domRpcResult) {
192 notificationHandler.addNotificationFilter(filter);
196 public void onFailure(final Throwable t) {
197 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly", t);
202 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
203 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
206 protected void handleSalInitializationSuccess(final SchemaContext result, final NetconfSessionPreferences remoteSessionCapabilities, final DOMRpcService deviceRpc) {
207 final BaseSchema baseSchema =
208 remoteSessionCapabilities.isNotificationsSupported() ?
209 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
210 BaseSchema.BASE_NETCONF_CTX;
211 messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
213 updateTransformer(messageTransformer);
214 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
215 salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc);
216 notificationHandler.onRemoteSchemaUp(messageTransformer);
218 LOG.info("{}: Netconf connector initialized successfully", id);
221 protected void handleSalInitializationFailure(final Throwable t, final RemoteDeviceCommunicator<NetconfMessage> listener) {
222 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, t);
224 onRemoteSessionDown();
225 resetMessageTransformer();
229 * Set the transformer to null as is in initial state
231 private void resetMessageTransformer() {
232 updateTransformer(null);
235 private void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
236 messageTransformer = transformer;
239 private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
240 final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
241 for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
242 sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
243 PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
248 public void onRemoteSessionDown() {
249 notificationHandler.onRemoteSchemaDown();
251 salFacade.onDeviceDisconnected();
252 for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration : sourceRegistrations) {
253 sourceRegistration.close();
255 resetMessageTransformer();
259 public void onRemoteSessionFailed(final Throwable throwable) {
260 salFacade.onDeviceFailed(throwable);
264 public void onNotification(final NetconfMessage notification) {
265 notificationHandler.handleNotification(notification);
269 * Just a transfer object containing schema related dependencies. Injected in constructor.
271 public static class SchemaResourcesDTO {
272 private final SchemaSourceRegistry schemaRegistry;
273 private final SchemaRepository schemaRepository;
274 private final SchemaContextFactory schemaContextFactory;
275 private final NetconfDeviceSchemasResolver stateSchemasResolver;
277 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
278 final SchemaRepository schemaRepository,
279 final SchemaContextFactory schemaContextFactory,
280 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
281 this.schemaRegistry = Preconditions.checkNotNull(schemaRegistry);
282 this.schemaRepository = Preconditions.checkNotNull(schemaRepository);
283 this.schemaContextFactory = Preconditions.checkNotNull(schemaContextFactory);
284 this.stateSchemasResolver = Preconditions.checkNotNull(deviceSchemasResolver);
287 public SchemaSourceRegistry getSchemaRegistry() {
288 return schemaRegistry;
291 public SchemaRepository getSchemaRepository() {
292 return schemaRepository;
295 public SchemaContextFactory getSchemaContextFactory() {
296 return schemaContextFactory;
299 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
300 return stateSchemasResolver;
305 * Schema building callable.
307 private static class DeviceSourcesResolver implements Callable<DeviceSources> {
309 private final NetconfDeviceRpc deviceRpc;
310 private final NetconfSessionPreferences remoteSessionCapabilities;
311 private final RemoteDeviceId id;
312 private final NetconfDeviceSchemasResolver stateSchemasResolver;
314 DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities,
315 final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver) {
316 this.deviceRpc = deviceRpc;
317 this.remoteSessionCapabilities = remoteSessionCapabilities;
319 this.stateSchemasResolver = stateSchemasResolver;
322 public DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver, final NetconfDeviceRpc rpcForMonitoring) {
323 this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver);
327 public DeviceSources call() throws Exception {
328 final NetconfDeviceSchemas availableSchemas = stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
329 LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id, availableSchemas.getAvailableYangSchemasQNames());
331 final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
332 final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
334 final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
335 if (!requiredSourcesNotProvided.isEmpty()) {
336 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}",
337 id, requiredSourcesNotProvided);
338 LOG.warn("{}: Attempting to build schema context from required sources", id);
341 // Here all the sources reported in netconf monitoring are merged with those reported in hello.
342 // It is necessary to perform this since submodules are not mentioned in hello but still required.
343 // This clashes with the option of a user to specify supported yang models manually in configuration for netconf-connector
344 // and as a result one is not able to fully override yang models of a device. It is only possible to add additional models.
345 final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
346 if (!providedSourcesNotRequired.isEmpty()) {
347 LOG.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}",
348 id, providedSourcesNotRequired);
349 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
350 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
351 requiredSources.addAll(providedSourcesNotRequired);
354 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
355 if(availableSchemas instanceof LibraryModulesSchemas) {
356 sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
357 ((LibraryModulesSchemas) availableSchemas).getAvailableModels());
359 sourceProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
362 return new DeviceSources(requiredSources, providedSources, sourceProvider);
367 * Contains RequiredSources - sources from capabilities.
369 private static final class DeviceSources {
370 private final Set<QName> requiredSources;
371 private final Set<QName> providedSources;
372 private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
374 public DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
375 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
376 this.requiredSources = requiredSources;
377 this.providedSources = providedSources;
378 this.sourceProvider = sourceProvider;
381 public Set<QName> getRequiredSourcesQName() {
382 return requiredSources;
385 public Set<QName> getProvidedSourcesQName() {
386 return providedSources;
389 public Collection<SourceIdentifier> getRequiredSources() {
390 return Collections2.transform(requiredSources, QNAME_TO_SOURCE_ID_FUNCTION);
393 public Collection<SourceIdentifier> getProvidedSources() {
394 return Collections2.transform(providedSources, QNAME_TO_SOURCE_ID_FUNCTION);
397 public SchemaSourceProvider<YangTextSchemaSource> getSourceProvider() {
398 return sourceProvider;
403 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
405 private final class SchemaSetup implements Runnable {
406 private final DeviceSources deviceSources;
407 private final NetconfSessionPreferences remoteSessionCapabilities;
408 private final RemoteDeviceCommunicator<NetconfMessage> listener;
409 private final NetconfDeviceCapabilities capabilities;
411 public SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceCommunicator<NetconfMessage> listener) {
412 this.deviceSources = deviceSources;
413 this.remoteSessionCapabilities = remoteSessionCapabilities;
414 this.listener = listener;
415 this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
421 final Collection<SourceIdentifier> requiredSources = deviceSources.getRequiredSources();
422 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
424 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
425 UnavailableCapability.FailureReason.MissingSource);
427 requiredSources.removeAll(missingSources);
428 setUpSchema(requiredSources);
431 private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> requiredSources) {
433 return requiredSources.parallelStream().filter(sourceIdentifier -> {
434 boolean remove = false;
436 schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).checkedGet();
437 } catch (SchemaSourceException e) {
441 }).collect(Collectors.toList());
445 * Build schema context, in case of success or final failure notify device
447 private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
448 while (!requiredSources.isEmpty()) {
449 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
451 final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture = schemaContextFactory.createSchemaContext(requiredSources);
452 final SchemaContext result = schemaBuilderFuture.checkedGet();
453 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
454 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), capabilities.getUnresolvedCapabilites().keySet());
455 capabilities.addCapabilities(filteredQNames);
456 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps());
457 handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
459 } catch (final Throwable t) {
460 if (t instanceof MissingSchemaSourceException){
461 requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t);
462 } else if (t instanceof SchemaResolutionException) {
463 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
464 // that might be wrapping a MissingSchemaSourceException so we need to look
465 // at the cause of the exception to make sure we don't misinterpret it.
466 if (t.getCause() instanceof MissingSchemaSourceException) {
467 requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t.getCause());
470 requiredSources = handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t);
472 // unknown error, fail
473 handleSalInitializationFailure(t, listener);
478 // No more sources, fail
479 final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context");
480 handleSalInitializationFailure(cause, listener);
481 salFacade.onDeviceFailed(cause);
484 private Collection<SourceIdentifier> handleMissingSchemaSourceException(final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException t) {
485 // In case source missing, try without it
486 final SourceIdentifier missingSource = t.getSourceId();
487 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
488 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", t);
489 final Collection<QName> qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
490 if (!qNameOfMissingSource.isEmpty()) {
491 capabilities.addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
493 return stripUnavailableSource(requiredSources, missingSource);
496 private Collection<SourceIdentifier> handleSchemaResolutionException(final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
497 // In case resolution error, try only with resolved sources
498 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
499 // FIXME Do we really have assurance that these two cases cannot happen at once?
500 if (resolutionException.getFailedSource() != null) {
501 // flawed model - exclude it
502 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
503 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, failedSourceId);
504 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, resolutionException);
505 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
506 UnavailableCapability.FailureReason.UnableToResolve);
507 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
509 // unsatisfied imports
510 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
511 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
512 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
513 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", resolutionException);
514 return resolutionException.getResolvedSources();
517 protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
518 return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
521 private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources, final SourceIdentifier sIdToRemove) {
522 final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
523 final boolean removed = sourceIdentifiers.remove(sIdToRemove);
524 Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources);
525 return sourceIdentifiers;
528 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
529 final Collection<QName> qNames = Collections2.transform(identifiers, new Function<SourceIdentifier, QName>() {
531 public QName apply(final SourceIdentifier sourceIdentifier) {
532 return getQNameFromSourceIdentifier(sourceIdentifier);
536 if (qNames.isEmpty()) {
537 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, identifiers);
539 return Collections2.filter(qNames, Predicates.notNull());
542 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
543 // Required sources are all required and provided merged in DeviceSourcesResolver
544 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
545 if(qname.getLocalName().equals(identifier.getName()) == false) {
549 if(identifier.getRevision().equals(SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION) &&
550 qname.getRevision() == null) {
554 if (qname.getFormattedRevision().equals(identifier.getRevision())) {
558 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier, deviceSources.getRequiredSourcesQName());
559 // return null since we cannot find the QName, this capability will be removed from required sources and not reported as unresolved-capability