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;
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.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;
27 import java.util.Optional;
29 import java.util.concurrent.Callable;
30 import java.util.concurrent.ExecutionException;
31 import java.util.stream.Collectors;
32 import org.checkerframework.checker.lock.qual.GuardedBy;
33 import org.opendaylight.mdsal.dom.api.DOMNotification;
34 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
35 import org.opendaylight.mdsal.dom.api.DOMRpcService;
36 import org.opendaylight.netconf.api.NetconfMessage;
37 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
38 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
39 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
40 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
41 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
42 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
43 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
44 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
45 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
47 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
48 import org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
49 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
50 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
51 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
52 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
53 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
59 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
60 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
61 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
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.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
75 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
77 public class NetconfDevice
78 implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
80 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
82 protected final RemoteDeviceId id;
83 protected final SchemaContextFactory schemaContextFactory;
84 protected final SchemaSourceRegistry schemaRegistry;
85 protected final SchemaRepository schemaRepository;
87 protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations =
90 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
91 private final ListeningExecutorService processingExecutor;
92 private final DeviceActionFactory deviceActionFactory;
93 private final NetconfDeviceSchemasResolver stateSchemasResolver;
94 private final NotificationHandler notificationHandler;
95 private final boolean reconnectOnSchemasChange;
98 private boolean connected = false;
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
105 * even before the schemas of remote device are downloaded.
107 static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener,
108 final boolean notificationSupport) {
109 final BaseSchema baseSchema = resolveBaseSchema(notificationSupport);
111 return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener,
112 new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
115 private static BaseSchema resolveBaseSchema(final boolean notificationSupport) {
116 return notificationSupport ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
119 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
120 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
121 final ListeningExecutorService globalProcessingExecutor,
122 final boolean reconnectOnSchemasChange) {
123 this(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null);
126 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
127 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
128 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
129 final DeviceActionFactory deviceActionFactory) {
131 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
132 this.deviceActionFactory = deviceActionFactory;
133 this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
134 this.schemaRepository = schemaResourcesDTO.getSchemaRepository();
135 this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
136 this.salFacade = salFacade;
137 this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
138 this.processingExecutor = requireNonNull(globalProcessingExecutor);
139 this.notificationHandler = new NotificationHandler(salFacade, id);
143 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
144 final NetconfDeviceCommunicator listener) {
145 // SchemaContext setup has to be performed in a dedicated thread since
146 // we are in a netty thread in this method
147 // Yang models are being downloaded in this method and it would cause a
148 // deadlock if we used the netty thread
149 // http://netty.io/wiki/thread-model.html
151 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
153 final NetconfDeviceRpc initRpc =
154 getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
155 final DeviceSourcesResolver task =
156 new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc,
157 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()).getSchemaContext());
158 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
160 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
161 registerToBaseNetconfStream(initRpc, listener);
164 final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
166 public void onSuccess(final DeviceSources result) {
167 addProvidedSourcesToSchemaRegistry(result);
171 private void setUpSchema(final DeviceSources result) {
172 processingExecutor.submit(new SchemaSetup(result, remoteSessionCapabilities, listener));
176 public void onFailure(final Throwable throwable) {
177 LOG.warn("{}: Unexpected error resolving device sources", id, throwable);
178 handleSalInitializationFailure(throwable, listener);
182 Futures.addCallback(sourceResolverFuture, resolvedSourceCallback, MoreExecutors.directExecutor());
185 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
186 final NetconfDeviceCommunicator listener) {
187 // TODO check whether the model describing create subscription is present in schema
188 // Perhaps add a default schema context to support create-subscription if the model was not provided
189 // (same as what we do for base netconf operations in transformer)
190 final ListenableFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
191 NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME),
192 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
194 final NotificationHandler.NotificationFilter filter = new NotificationHandler.NotificationFilter() {
196 public Optional<DOMNotification> filterNotification(final DOMNotification notification) {
197 if (isCapabilityChanged(notification)) {
198 LOG.info("{}: Schemas change detected, reconnecting", id);
199 // Only disconnect is enough,
200 // the reconnecting nature of the connector will take care of reconnecting
201 listener.disconnect();
202 return Optional.empty();
204 return Optional.of(notification);
207 private boolean isCapabilityChanged(final DOMNotification notification) {
208 return notification.getBody().getNodeType().equals(NetconfCapabilityChange.QNAME);
212 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
214 public void onSuccess(final DOMRpcResult domRpcResult) {
215 notificationHandler.addNotificationFilter(filter);
219 public void onFailure(final Throwable throwable) {
220 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
223 }, MoreExecutors.directExecutor());
226 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
227 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
230 private synchronized void handleSalInitializationSuccess(final SchemaContext result,
231 final NetconfSessionPreferences remoteSessionCapabilities,
232 final DOMRpcService deviceRpc,
233 final RemoteDeviceCommunicator<NetconfMessage> listener) {
234 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
235 //since salFacade.onDeviceDisconnected was already called.
237 final BaseSchema baseSchema =
238 remoteSessionCapabilities.isNotificationsSupported()
239 ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
240 this.messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
242 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
243 this.salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
244 this.deviceActionFactory == null ? null : this.deviceActionFactory.createDeviceAction(
245 this.messageTransformer, listener, result));
246 this.notificationHandler.onRemoteSchemaUp(this.messageTransformer);
248 LOG.info("{}: Netconf connector initialized successfully", id);
250 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
254 private void handleSalInitializationFailure(final Throwable throwable,
255 final RemoteDeviceCommunicator<NetconfMessage> listener) {
256 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
258 onRemoteSessionDown();
259 resetMessageTransformer();
263 * Set the transformer to null as is in initial state.
265 private void resetMessageTransformer() {
266 updateTransformer(null);
269 private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
270 messageTransformer = transformer;
273 private synchronized void setConnected(final boolean connected) {
274 this.connected = connected;
277 private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
278 final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
279 for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
280 sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
281 PotentialSchemaSource.create(
282 sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
287 public void onRemoteSessionDown() {
289 notificationHandler.onRemoteSchemaDown();
291 salFacade.onDeviceDisconnected();
292 for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration
293 : sourceRegistrations) {
294 sourceRegistration.close();
296 resetMessageTransformer();
300 public void onRemoteSessionFailed(final Throwable throwable) {
302 salFacade.onDeviceFailed(throwable);
306 public void onNotification(final NetconfMessage notification) {
307 notificationHandler.handleNotification(notification);
311 * Just a transfer object containing schema related dependencies. Injected in constructor.
313 public static class SchemaResourcesDTO {
314 private final SchemaSourceRegistry schemaRegistry;
315 private final SchemaRepository schemaRepository;
316 private final SchemaContextFactory schemaContextFactory;
317 private final NetconfDeviceSchemasResolver stateSchemasResolver;
319 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
320 final SchemaRepository schemaRepository,
321 final SchemaContextFactory schemaContextFactory,
322 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
323 this.schemaRegistry = requireNonNull(schemaRegistry);
324 this.schemaRepository = requireNonNull(schemaRepository);
325 this.schemaContextFactory = requireNonNull(schemaContextFactory);
326 this.stateSchemasResolver = requireNonNull(deviceSchemasResolver);
329 public SchemaSourceRegistry getSchemaRegistry() {
330 return schemaRegistry;
333 public SchemaRepository getSchemaRepository() {
334 return schemaRepository;
337 public SchemaContextFactory getSchemaContextFactory() {
338 return schemaContextFactory;
341 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
342 return stateSchemasResolver;
347 * Schema building callable.
349 private static class DeviceSourcesResolver implements Callable<DeviceSources> {
351 private final NetconfDeviceRpc deviceRpc;
352 private final NetconfSessionPreferences remoteSessionCapabilities;
353 private final RemoteDeviceId id;
354 private final NetconfDeviceSchemasResolver stateSchemasResolver;
355 private final SchemaContext schemaContext;
357 DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc,
358 final NetconfSessionPreferences remoteSessionCapabilities,
359 final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver,
360 final SchemaContext schemaContext) {
361 this.deviceRpc = deviceRpc;
362 this.remoteSessionCapabilities = remoteSessionCapabilities;
364 this.stateSchemasResolver = stateSchemasResolver;
365 this.schemaContext = schemaContext;
368 DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
369 final NetconfDeviceSchemasResolver stateSchemasResolver,
370 final NetconfDeviceRpc rpcForMonitoring, final SchemaContext schemaCtx) {
371 this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver, schemaCtx);
375 public DeviceSources call() {
376 final NetconfDeviceSchemas availableSchemas =
377 stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id, schemaContext);
378 LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id,
379 availableSchemas.getAvailableYangSchemasQNames());
381 final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
382 final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
384 final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
385 if (!requiredSourcesNotProvided.isEmpty()) {
386 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities,"
387 + " required but not provided: {}", id, requiredSourcesNotProvided);
388 LOG.warn("{}: Attempting to build schema context from required sources", id);
391 // Here all the sources reported in netconf monitoring are merged with those reported in hello.
392 // It is necessary to perform this since submodules are not mentioned in hello but still required.
393 // This clashes with the option of a user to specify supported yang models manually in configuration
394 // for netconf-connector and as a result one is not able to fully override yang models of a device.
395 // It is only possible to add additional models.
396 final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
397 if (!providedSourcesNotRequired.isEmpty()) {
398 LOG.warn("{}: Netconf device provides additional yang models not reported in "
399 + "hello message capabilities: {}", id, providedSourcesNotRequired);
400 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
401 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
402 requiredSources.addAll(providedSourcesNotRequired);
405 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
406 if (availableSchemas instanceof LibraryModulesSchemas) {
407 sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
408 ((LibraryModulesSchemas) availableSchemas).getAvailableModels());
410 sourceProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
413 return new DeviceSources(requiredSources, providedSources, sourceProvider);
418 * Contains RequiredSources - sources from capabilities.
420 private static final class DeviceSources {
421 private final Set<QName> requiredSources;
422 private final Set<QName> providedSources;
423 private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
425 DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
426 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
427 this.requiredSources = requiredSources;
428 this.providedSources = providedSources;
429 this.sourceProvider = sourceProvider;
432 public Set<QName> getRequiredSourcesQName() {
433 return requiredSources;
436 public Set<QName> getProvidedSourcesQName() {
437 return providedSources;
440 public Collection<SourceIdentifier> getRequiredSources() {
441 return Collections2.transform(requiredSources, DeviceSources::toSourceId);
444 public Collection<SourceIdentifier> getProvidedSources() {
445 return Collections2.transform(providedSources, DeviceSources::toSourceId);
448 public SchemaSourceProvider<YangTextSchemaSource> getSourceProvider() {
449 return sourceProvider;
452 private static SourceIdentifier toSourceId(final QName input) {
453 return RevisionSourceIdentifier.create(input.getLocalName(), input.getRevision());
458 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
460 private final class SchemaSetup implements Runnable {
461 private final DeviceSources deviceSources;
462 private final NetconfSessionPreferences remoteSessionCapabilities;
463 private final RemoteDeviceCommunicator<NetconfMessage> listener;
464 private final NetconfDeviceCapabilities capabilities;
466 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities,
467 final RemoteDeviceCommunicator<NetconfMessage> listener) {
468 this.deviceSources = deviceSources;
469 this.remoteSessionCapabilities = remoteSessionCapabilities;
470 this.listener = listener;
471 this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
477 final Collection<SourceIdentifier> requiredSources = deviceSources.getRequiredSources();
478 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
480 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
481 UnavailableCapability.FailureReason.MissingSource);
483 requiredSources.removeAll(missingSources);
484 setUpSchema(requiredSources);
487 private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> requiredSources) {
488 return requiredSources.parallelStream().filter(sourceIdentifier -> {
490 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
492 } catch (InterruptedException | ExecutionException e) {
495 }).collect(Collectors.toList());
499 * Build schema context, in case of success or final failure notify device.
501 * @param requiredSources required sources
503 @SuppressWarnings("checkstyle:IllegalCatch")
504 private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
505 while (!requiredSources.isEmpty()) {
506 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
508 final ListenableFuture<SchemaContext> schemaBuilderFuture = schemaContextFactory
509 .createSchemaContext(requiredSources);
510 final SchemaContext result = schemaBuilderFuture.get();
511 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
512 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
513 capabilities.getUnresolvedCapabilites().keySet());
514 capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
515 .setCapability(entry.toString()).setCapabilityOrigin(
516 remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
517 .collect(Collectors.toList()));
519 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
520 .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
521 .setCapability(entry).setCapabilityOrigin(
522 remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
523 .collect(Collectors.toList()));
525 handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result),
528 } catch (final ExecutionException e) {
529 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
530 // that might be wrapping a MissingSchemaSourceException so we need to look
531 // at the cause of the exception to make sure we don't misinterpret it.
532 final Throwable cause = e.getCause();
534 if (cause instanceof MissingSchemaSourceException) {
535 requiredSources = handleMissingSchemaSourceException(
536 requiredSources, (MissingSchemaSourceException) cause);
539 if (cause instanceof SchemaResolutionException) {
540 requiredSources = handleSchemaResolutionException(requiredSources,
541 (SchemaResolutionException) cause);
543 handleSalInitializationFailure(e, listener);
546 } catch (final Exception e) {
547 // unknown error, fail
548 handleSalInitializationFailure(e, listener);
552 // No more sources, fail
553 final IllegalStateException cause = new IllegalStateException(id + ": No more sources for schema context");
554 handleSalInitializationFailure(cause, listener);
555 salFacade.onDeviceFailed(cause);
558 private Collection<SourceIdentifier> handleMissingSchemaSourceException(
559 final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException exception) {
560 // In case source missing, try without it
561 final SourceIdentifier missingSource = exception.getSourceId();
562 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
564 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
565 id, missingSource, exception);
566 final Collection<QName> qNameOfMissingSource =
567 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
568 if (!qNameOfMissingSource.isEmpty()) {
569 capabilities.addUnresolvedCapabilities(
570 qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
572 return stripUnavailableSource(requiredSources, missingSource);
575 private Collection<SourceIdentifier> handleSchemaResolutionException(
576 final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
577 // In case resolution error, try only with resolved sources
578 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
579 // FIXME Do we really have assurance that these two cases cannot happen at once?
580 if (resolutionException.getFailedSource() != null) {
581 // flawed model - exclude it
582 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
583 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
585 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
586 id, failedSourceId, resolutionException);
587 capabilities.addUnresolvedCapabilities(
588 getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
589 UnavailableCapability.FailureReason.UnableToResolve);
590 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
592 // unsatisfied imports
593 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
594 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
595 UnavailableCapability.FailureReason.UnableToResolve);
596 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
597 id, resolutionException.getUnsatisfiedImports());
598 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
599 id, resolutionException.getUnsatisfiedImports(), resolutionException);
600 return resolutionException.getResolvedSources();
603 protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
604 return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
607 private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources,
608 final SourceIdentifier sourceIdToRemove) {
609 final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
610 checkState(sourceIdentifiers.remove(sourceIdToRemove),
611 "%s: Trying to remove %s from %s failed", id, sourceIdToRemove, requiredSources);
612 return sourceIdentifiers;
615 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
616 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
618 if (qNames.isEmpty()) {
619 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
622 return Collections2.filter(qNames, Predicates.notNull());
625 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
626 // Required sources are all required and provided merged in DeviceSourcesResolver
627 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
628 if (!qname.getLocalName().equals(identifier.getName())) {
632 if (identifier.getRevision().equals(qname.getRevision())) {
636 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
637 deviceSources.getRequiredSourcesQName());
638 // return null since we cannot find the QName,
639 // this capability will be removed from required sources and not reported as unresolved-capability