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 java.util.Objects.requireNonNull;
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.FluentFuture;
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 io.netty.util.concurrent.EventExecutor;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.LinkedList;
28 import java.util.List;
29 import java.util.Optional;
31 import java.util.concurrent.Callable;
32 import java.util.concurrent.ExecutionException;
33 import java.util.concurrent.TimeUnit;
34 import java.util.stream.Collectors;
35 import javax.annotation.Nonnull;
36 import javax.annotation.concurrent.GuardedBy;
37 import org.opendaylight.mdsal.dom.api.DOMNotification;
38 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
39 import org.opendaylight.mdsal.dom.api.DOMRpcService;
40 import org.opendaylight.netconf.api.NetconfMessage;
41 import org.opendaylight.netconf.sal.connect.api.DeviceActionFactory;
42 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
43 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
44 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
45 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
46 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
47 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
50 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
51 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
52 import org.opendaylight.netconf.sal.connect.netconf.schema.NetconfRemoteSchemaYangSourceProvider;
53 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
54 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
55 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
56 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
57 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.optional.rev190614.NetconfNodeAugmentedOptional;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapabilityBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.unavailable.capabilities.UnavailableCapability;
63 import org.opendaylight.yangtools.yang.common.QName;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
65 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
66 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
67 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
68 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
69 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
70 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
71 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
72 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
73 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
74 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
75 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
80 * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
82 public class NetconfDevice
83 implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
85 private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
87 protected final RemoteDeviceId id;
88 protected final SchemaContextFactory schemaContextFactory;
89 protected final SchemaSourceRegistry schemaRegistry;
90 protected final SchemaRepository schemaRepository;
92 protected final List<SchemaSourceRegistration<?>> sourceRegistrations = new ArrayList<>();
94 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
95 private final ListeningExecutorService processingExecutor;
96 private final DeviceActionFactory deviceActionFactory;
97 private final NetconfDeviceSchemasResolver stateSchemasResolver;
98 private final NotificationHandler notificationHandler;
99 private final boolean reconnectOnSchemasChange;
100 private final NetconfNode node;
101 private final EventExecutor eventExecutor;
102 private final NetconfNodeAugmentedOptional nodeOptional;
105 private boolean connected = false;
107 // Message transformer is constructed once the schemas are available
108 private MessageTransformer<NetconfMessage> messageTransformer;
111 * Create rpc implementation capable of handling RPC for monitoring and notifications
112 * even before the schemas of remote device are downloaded.
114 static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener,
115 final boolean notificationSupport) {
116 final BaseSchema baseSchema = resolveBaseSchema(notificationSupport);
118 return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener,
119 new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
122 private static BaseSchema resolveBaseSchema(final boolean notificationSupport) {
123 return notificationSupport ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
126 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
127 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
128 final ListeningExecutorService globalProcessingExecutor,
129 final boolean reconnectOnSchemasChange) {
130 this(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, reconnectOnSchemasChange, null, null, null,
134 public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
135 final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
136 final ListeningExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange,
137 final DeviceActionFactory deviceActionFactory, final NetconfNode node, final EventExecutor eventExecutor,
138 final NetconfNodeAugmentedOptional nodeOptional) {
140 this.reconnectOnSchemasChange = reconnectOnSchemasChange;
141 this.deviceActionFactory = deviceActionFactory;
143 this.eventExecutor = eventExecutor;
144 this.nodeOptional = nodeOptional;
145 this.schemaRegistry = schemaResourcesDTO.getSchemaRegistry();
146 this.schemaRepository = schemaResourcesDTO.getSchemaRepository();
147 this.schemaContextFactory = schemaResourcesDTO.getSchemaContextFactory();
148 this.salFacade = salFacade;
149 this.stateSchemasResolver = schemaResourcesDTO.getStateSchemasResolver();
150 this.processingExecutor = requireNonNull(globalProcessingExecutor);
151 this.notificationHandler = new NotificationHandler(salFacade, id);
155 public void onRemoteSessionUp(final NetconfSessionPreferences remoteSessionCapabilities,
156 final NetconfDeviceCommunicator listener) {
157 // SchemaContext setup has to be performed in a dedicated thread since
158 // we are in a netty thread in this method
159 // Yang models are being downloaded in this method and it would cause a
160 // deadlock if we used the netty thread
161 // http://netty.io/wiki/thread-model.html
163 LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
165 final NetconfDeviceRpc initRpc =
166 getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
167 final DeviceSourcesResolver task =
168 new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc,
169 resolveBaseSchema(remoteSessionCapabilities.isNotificationsSupported()).getSchemaContext());
170 final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
172 if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
173 registerToBaseNetconfStream(initRpc, listener);
176 final FutureCallback<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
178 public void onSuccess(@Nonnull final DeviceSources result) {
179 addProvidedSourcesToSchemaRegistry(result);
183 private void setUpSchema(final DeviceSources result) {
184 processingExecutor.submit(new SchemaSetup(result, remoteSessionCapabilities, listener));
188 public void onFailure(final Throwable throwable) {
189 LOG.warn("{}: Unexpected error resolving device sources", id, throwable);
190 handleSalInitializationFailure(throwable, listener);
194 Futures.addCallback(sourceResolverFuture, resolvedSourceCallback, MoreExecutors.directExecutor());
197 private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
198 final NetconfDeviceCommunicator listener) {
199 // TODO check whether the model describing create subscription is present in schema
200 // Perhaps add a default schema context to support create-subscription if the model was not provided
201 // (same as what we do for base netconf operations in transformer)
202 final FluentFuture<DOMRpcResult> rpcResultListenableFuture = deviceRpc.invokeRpc(
203 NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME),
204 NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
206 final NotificationHandler.NotificationFilter filter = new NotificationHandler.NotificationFilter() {
208 public Optional<DOMNotification> filterNotification(final DOMNotification notification) {
209 if (isCapabilityChanged(notification)) {
210 LOG.info("{}: Schemas change detected, reconnecting", id);
211 // Only disconnect is enough,
212 // the reconnecting nature of the connector will take care of reconnecting
213 listener.disconnect();
214 return Optional.empty();
216 return Optional.of(notification);
219 private boolean isCapabilityChanged(final DOMNotification notification) {
220 return notification.getBody().getNodeType().equals(NetconfCapabilityChange.QNAME);
224 Futures.addCallback(rpcResultListenableFuture, new FutureCallback<DOMRpcResult>() {
226 public void onSuccess(final DOMRpcResult domRpcResult) {
227 notificationHandler.addNotificationFilter(filter);
231 public void onFailure(final Throwable throwable) {
232 LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
235 }, MoreExecutors.directExecutor());
238 private boolean shouldListenOnSchemaChange(final NetconfSessionPreferences remoteSessionCapabilities) {
239 return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
242 private synchronized void handleSalInitializationSuccess(final SchemaContext result,
243 final NetconfSessionPreferences remoteSessionCapabilities,
244 final DOMRpcService deviceRpc,
245 final RemoteDeviceCommunicator<NetconfMessage> listener) {
246 //NetconfDevice.SchemaSetup can complete after NetconfDeviceCommunicator was closed. In that case do nothing,
247 //since salFacade.onDeviceDisconnected was already called.
249 final BaseSchema baseSchema =
250 remoteSessionCapabilities.isNotificationsSupported()
251 ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
252 this.messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
254 updateTransformer(this.messageTransformer);
255 // salFacade.onDeviceConnected has to be called before the notification handler is initialized
256 this.salFacade.onDeviceConnected(result, remoteSessionCapabilities, deviceRpc,
257 this.deviceActionFactory == null ? null : this.deviceActionFactory.createDeviceAction(
258 this.messageTransformer, listener, result));
259 this.notificationHandler.onRemoteSchemaUp(this.messageTransformer);
261 LOG.info("{}: Netconf connector initialized successfully", id);
263 LOG.warn("{}: Device communicator was closed before schema setup finished.", id);
267 private void handleSalInitializationFailure(final Throwable throwable,
268 final RemoteDeviceCommunicator<NetconfMessage> listener) {
269 LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
271 onRemoteSessionDown();
272 resetMessageTransformer();
276 * Set the transformer to null as is in initial state.
278 private void resetMessageTransformer() {
279 updateTransformer(null);
282 private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> transformer) {
283 messageTransformer = transformer;
286 private synchronized void setConnected(final boolean connected) {
287 this.connected = connected;
290 private void addProvidedSourcesToSchemaRegistry(final DeviceSources deviceSources) {
291 final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
292 for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
293 sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
294 PotentialSchemaSource.create(
295 sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
300 public void onRemoteSessionDown() {
302 notificationHandler.onRemoteSchemaDown();
304 salFacade.onDeviceDisconnected();
305 sourceRegistrations.forEach(SchemaSourceRegistration::close);
306 sourceRegistrations.clear();
307 resetMessageTransformer();
311 public void onRemoteSessionFailed(final Throwable throwable) {
313 salFacade.onDeviceFailed(throwable);
317 public void onNotification(final NetconfMessage notification) {
318 notificationHandler.handleNotification(notification);
322 * Just a transfer object containing schema related dependencies. Injected in constructor.
324 public static class SchemaResourcesDTO {
325 private final SchemaSourceRegistry schemaRegistry;
326 private final SchemaRepository schemaRepository;
327 private final SchemaContextFactory schemaContextFactory;
328 private final NetconfDeviceSchemasResolver stateSchemasResolver;
330 public SchemaResourcesDTO(final SchemaSourceRegistry schemaRegistry,
331 final SchemaRepository schemaRepository,
332 final SchemaContextFactory schemaContextFactory,
333 final NetconfDeviceSchemasResolver deviceSchemasResolver) {
334 this.schemaRegistry = Preconditions.checkNotNull(schemaRegistry);
335 this.schemaRepository = Preconditions.checkNotNull(schemaRepository);
336 this.schemaContextFactory = Preconditions.checkNotNull(schemaContextFactory);
337 this.stateSchemasResolver = Preconditions.checkNotNull(deviceSchemasResolver);
340 public SchemaSourceRegistry getSchemaRegistry() {
341 return schemaRegistry;
344 public SchemaRepository getSchemaRepository() {
345 return schemaRepository;
348 public SchemaContextFactory getSchemaContextFactory() {
349 return schemaContextFactory;
352 public NetconfDeviceSchemasResolver getStateSchemasResolver() {
353 return stateSchemasResolver;
358 * Schema building callable.
360 private static class DeviceSourcesResolver implements Callable<DeviceSources> {
362 private final NetconfDeviceRpc deviceRpc;
363 private final NetconfSessionPreferences remoteSessionCapabilities;
364 private final RemoteDeviceId id;
365 private final NetconfDeviceSchemasResolver stateSchemasResolver;
366 private final SchemaContext schemaContext;
368 DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc,
369 final NetconfSessionPreferences remoteSessionCapabilities,
370 final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver,
371 final SchemaContext schemaContext) {
372 this.deviceRpc = deviceRpc;
373 this.remoteSessionCapabilities = remoteSessionCapabilities;
375 this.stateSchemasResolver = stateSchemasResolver;
376 this.schemaContext = schemaContext;
379 DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
380 final NetconfDeviceSchemasResolver stateSchemasResolver,
381 final NetconfDeviceRpc rpcForMonitoring, final SchemaContext schemaCtx) {
382 this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver, schemaCtx);
386 public DeviceSources call() {
387 final NetconfDeviceSchemas availableSchemas =
388 stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id, schemaContext);
389 LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id,
390 availableSchemas.getAvailableYangSchemasQNames());
392 final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
393 final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
395 final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
396 if (!requiredSourcesNotProvided.isEmpty()) {
397 LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities,"
398 + " required but not provided: {}", id, requiredSourcesNotProvided);
399 LOG.warn("{}: Attempting to build schema context from required sources", id);
402 // Here all the sources reported in netconf monitoring are merged with those reported in hello.
403 // It is necessary to perform this since submodules are not mentioned in hello but still required.
404 // This clashes with the option of a user to specify supported yang models manually in configuration
405 // for netconf-connector and as a result one is not able to fully override yang models of a device.
406 // It is only possible to add additional models.
407 final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
408 if (!providedSourcesNotRequired.isEmpty()) {
409 LOG.warn("{}: Netconf device provides additional yang models not reported in "
410 + "hello message capabilities: {}", id, providedSourcesNotRequired);
411 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
412 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
413 requiredSources.addAll(providedSourcesNotRequired);
416 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
417 if (availableSchemas instanceof LibraryModulesSchemas) {
418 sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
419 ((LibraryModulesSchemas) availableSchemas).getAvailableModels());
421 sourceProvider = new NetconfRemoteSchemaYangSourceProvider(id, deviceRpc);
424 return new DeviceSources(requiredSources, providedSources, sourceProvider);
429 * Contains RequiredSources - sources from capabilities.
431 private static final class DeviceSources {
432 private final Set<QName> requiredSources;
433 private final Set<QName> providedSources;
434 private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
436 DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
437 final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
438 this.requiredSources = requiredSources;
439 this.providedSources = providedSources;
440 this.sourceProvider = sourceProvider;
443 public Set<QName> getRequiredSourcesQName() {
444 return requiredSources;
447 public Set<QName> getProvidedSourcesQName() {
448 return providedSources;
451 public Collection<SourceIdentifier> getRequiredSources() {
452 return Collections2.transform(requiredSources, DeviceSources::toSourceId);
455 public Collection<SourceIdentifier> getProvidedSources() {
456 return Collections2.transform(providedSources, DeviceSources::toSourceId);
459 public SchemaSourceProvider<YangTextSchemaSource> getSourceProvider() {
460 return sourceProvider;
463 private static SourceIdentifier toSourceId(final QName input) {
464 return RevisionSourceIdentifier.create(input.getLocalName(), input.getRevision());
469 * Schema builder that tries to build schema context from provided sources or biggest subset of it.
471 private final class SchemaSetup implements Runnable {
472 private final DeviceSources deviceSources;
473 private final NetconfSessionPreferences remoteSessionCapabilities;
474 private final RemoteDeviceCommunicator<NetconfMessage> listener;
475 private final NetconfDeviceCapabilities capabilities;
477 SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities,
478 final RemoteDeviceCommunicator<NetconfMessage> listener) {
479 this.deviceSources = deviceSources;
480 this.remoteSessionCapabilities = remoteSessionCapabilities;
481 this.listener = listener;
482 this.capabilities = remoteSessionCapabilities.getNetconfDeviceCapabilities();
488 final Collection<SourceIdentifier> requiredSources = deviceSources.getRequiredSources();
489 final Collection<SourceIdentifier> missingSources = filterMissingSources(requiredSources);
491 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(missingSources),
492 UnavailableCapability.FailureReason.MissingSource);
494 requiredSources.removeAll(missingSources);
495 setUpSchema(requiredSources);
498 private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> requiredSources) {
499 return requiredSources.parallelStream().filter(sourceIdentifier -> {
501 schemaRepository.getSchemaSource(sourceIdentifier, YangTextSchemaSource.class).get();
503 } catch (InterruptedException | ExecutionException e) {
506 }).collect(Collectors.toList());
510 * Build schema context, in case of success or final failure notify device.
512 * @param requiredSources required sources
514 @SuppressWarnings("checkstyle:IllegalCatch")
515 private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
516 while (!requiredSources.isEmpty()) {
517 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
519 final ListenableFuture<SchemaContext> schemaBuilderFuture = schemaContextFactory
520 .createSchemaContext(requiredSources);
521 final SchemaContext result = schemaBuilderFuture.get();
522 LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
523 final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
524 capabilities.getUnresolvedCapabilites().keySet());
525 capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
526 .setCapability(entry.toString()).setCapabilityOrigin(
527 remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
528 .collect(Collectors.toList()));
530 capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
531 .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
532 .setCapability(entry).setCapabilityOrigin(
533 remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
534 .collect(Collectors.toList()));
536 handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result),
539 } catch (final ExecutionException e) {
540 // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
541 // that might be wrapping a MissingSchemaSourceException so we need to look
542 // at the cause of the exception to make sure we don't misinterpret it.
543 final Throwable cause = e.getCause();
545 if (cause instanceof MissingSchemaSourceException) {
546 requiredSources = handleMissingSchemaSourceException(
547 requiredSources, (MissingSchemaSourceException) cause);
550 if (cause instanceof SchemaResolutionException) {
551 requiredSources = handleSchemaResolutionException(requiredSources,
552 (SchemaResolutionException) cause);
554 handleSalInitializationFailure(e, listener);
557 } catch (final Exception e) {
558 // unknown error, fail
559 handleSalInitializationFailure(e, listener);
563 // No more sources, fail or try to reconnect
564 if (nodeOptional != null && nodeOptional.getIgnoreMissingSchemaSources().isAllowed()) {
565 eventExecutor.schedule(() -> {
566 LOG.warn("Reconnection is allowed! This can lead to unexpected errors at runtime.");
567 LOG.warn("{} : No more sources for schema context.", id);
568 LOG.info("{} : Try to remount device.", id);
569 onRemoteSessionDown();
570 salFacade.onDeviceReconnected(remoteSessionCapabilities, node);
571 }, nodeOptional.getIgnoreMissingSchemaSources().getReconnectTime(), TimeUnit.MILLISECONDS);
573 final IllegalStateException cause =
574 new IllegalStateException(id + ": No more sources for schema context");
575 handleSalInitializationFailure(cause, listener);
576 salFacade.onDeviceFailed(cause);
580 private Collection<SourceIdentifier> handleMissingSchemaSourceException(
581 final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException exception) {
582 // In case source missing, try without it
583 final SourceIdentifier missingSource = exception.getSourceId();
584 LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it",
586 LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
587 id, missingSource, exception);
588 final Collection<QName> qNameOfMissingSource =
589 getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
590 if (!qNameOfMissingSource.isEmpty()) {
591 capabilities.addUnresolvedCapabilities(
592 qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
594 return stripUnavailableSource(requiredSources, missingSource);
597 private Collection<SourceIdentifier> handleSchemaResolutionException(
598 final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
599 // In case resolution error, try only with resolved sources
600 // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
601 // FIXME Do we really have assurance that these two cases cannot happen at once?
602 if (resolutionException.getFailedSource() != null) {
603 // flawed model - exclude it
604 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
605 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
607 LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
608 id, failedSourceId, resolutionException);
609 capabilities.addUnresolvedCapabilities(
610 getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
611 UnavailableCapability.FailureReason.UnableToResolve);
612 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
614 // unsatisfied imports
615 final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
616 capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources),
617 UnavailableCapability.FailureReason.UnableToResolve);
618 LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
619 id, resolutionException.getUnsatisfiedImports());
620 LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
621 id, resolutionException.getUnsatisfiedImports(), resolutionException);
622 return resolutionException.getResolvedSources();
625 protected NetconfDeviceRpc getDeviceSpecificRpc(final SchemaContext result) {
626 return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
629 private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources,
630 final SourceIdentifier sourceIdToRemove) {
631 final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
632 final boolean removed = sourceIdentifiers.remove(sourceIdToRemove);
633 Preconditions.checkState(
634 removed, "{}: Trying to remove {} from {} failed", id, sourceIdToRemove, requiredSources);
635 return sourceIdentifiers;
638 private Collection<QName> getQNameFromSourceIdentifiers(final Collection<SourceIdentifier> identifiers) {
639 final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
641 if (qNames.isEmpty()) {
642 LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
645 return Collections2.filter(qNames, Predicates.notNull());
648 private QName getQNameFromSourceIdentifier(final SourceIdentifier identifier) {
649 // Required sources are all required and provided merged in DeviceSourcesResolver
650 for (final QName qname : deviceSources.getRequiredSourcesQName()) {
651 if (!qname.getLocalName().equals(identifier.getName())) {
655 if (identifier.getRevision().equals(qname.getRevision())) {
659 LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
660 deviceSources.getRequiredSourcesQName());
661 // return null since we cannot find the QName,
662 // this capability will be removed from required sources and not reported as unresolved-capability