2 * Copyright (c) 2015 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
9 package org.opendaylight.netconf.topology;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Strings;
14 import com.google.common.collect.Lists;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import io.netty.util.concurrent.EventExecutor;
20 import java.math.BigDecimal;
21 import java.net.InetSocketAddress;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
27 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
28 import org.opendaylight.controller.config.threadpool.ThreadPool;
29 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
30 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
31 import org.opendaylight.netconf.api.NetconfMessage;
32 import org.opendaylight.netconf.client.NetconfClientDispatcher;
33 import org.opendaylight.netconf.client.NetconfClientSessionListener;
34 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
35 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
36 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
37 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
38 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
39 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
40 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
41 import org.opendaylight.netconf.sal.connect.netconf.LibraryModulesSchemas;
42 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
43 import org.opendaylight.netconf.sal.connect.netconf.NetconfDeviceBuilder;
44 import org.opendaylight.netconf.sal.connect.netconf.NetconfStateSchemasResolverImpl;
45 import org.opendaylight.netconf.sal.connect.netconf.SchemalessNetconfDevice;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
47 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.UserPreferences;
50 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
51 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
52 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
53 import org.opendaylight.netconf.topology.api.NetconfTopology;
54 import org.opendaylight.netconf.topology.api.SchemaRepositoryProvider;
55 import org.opendaylight.protocol.framework.ReconnectStrategy;
56 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
57 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
58 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
59 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
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.AvailableCapability.CapabilityOrigin;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
64 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
65 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
66 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
67 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
68 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
69 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
70 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
71 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
72 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
73 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
74 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
75 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
79 public abstract class AbstractNetconfTopology implements NetconfTopology {
81 private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfTopology.class);
83 protected static final long DEFAULT_REQUEST_TIMEOUT_MILLIS = 60000L;
84 protected static final int DEFAULT_KEEPALIVE_DELAY = 0;
85 protected static final boolean DEFAULT_RECONNECT_ON_CHANGED_SCHEMA = false;
86 protected static final int DEFAULT_CONCURRENT_RPC_LIMIT = 0;
87 private static final int DEFAULT_MAX_CONNECTION_ATTEMPTS = 0;
88 private static final int DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS = 2000;
89 private static final long DEFAULT_CONNECTION_TIMEOUT_MILLIS = 20000L;
90 private static final BigDecimal DEFAULT_SLEEP_FACTOR = new BigDecimal(1.5);
92 // constants related to Schema Cache(s)
94 * Filesystem based caches are stored relative to the cache directory.
96 private static final String CACHE_DIRECTORY = "cache";
99 * The default cache directory relative to <code>CACHE_DIRECTORY</code>
101 private static final String DEFAULT_CACHE_DIRECTORY = "schema";
104 * The qualified schema cache directory <code>cache/schema</code>
106 private static final String QUALIFIED_DEFAULT_CACHE_DIRECTORY = CACHE_DIRECTORY + File.separator+ DEFAULT_CACHE_DIRECTORY;
109 * The name for the default schema repository
111 private static final String DEFAULT_SCHEMA_REPOSITORY_NAME = "sal-netconf-connector";
114 * The default schema repository in the case that one is not specified.
116 private static final SharedSchemaRepository DEFAULT_SCHEMA_REPOSITORY =
117 new SharedSchemaRepository(DEFAULT_SCHEMA_REPOSITORY_NAME);
120 * The default <code>FilesystemSchemaSourceCache</code>, which stores cached files in <code>cache/schema</code>.
122 private static final FilesystemSchemaSourceCache<YangTextSchemaSource> DEFAULT_CACHE =
123 new FilesystemSchemaSourceCache<>(DEFAULT_SCHEMA_REPOSITORY, YangTextSchemaSource.class,
124 new File(QUALIFIED_DEFAULT_CACHE_DIRECTORY));
127 * The default factory for creating <code>SchemaContext</code> instances.
129 private static final SchemaContextFactory DEFAULT_SCHEMA_CONTEXT_FACTORY =
130 DEFAULT_SCHEMA_REPOSITORY.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
133 * Keeps track of initialized Schema resources. A Map is maintained in which the key represents the name
134 * of the schema cache directory, and the value is a corresponding <code>SchemaResourcesDTO</code>. The
135 * <code>SchemaResourcesDTO</code> is essentially a container that allows for the extraction of the
136 * <code>SchemaRegistry</code> and <code>SchemaContextFactory</code> which should be used for a particular
137 * Netconf mount. Access to <code>schemaResourcesDTOs</code> should be surrounded by appropriate
138 * synchronization locks.
140 private static final Map<String, NetconfDevice.SchemaResourcesDTO> schemaResourcesDTOs = new HashMap<>();
142 // Initializes default constant instances for the case when the default schema repository
143 // directory cache/schema is used.
145 schemaResourcesDTOs.put(DEFAULT_CACHE_DIRECTORY,
146 new NetconfDevice.SchemaResourcesDTO(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY,
147 DEFAULT_SCHEMA_CONTEXT_FACTORY,
148 new NetconfStateSchemasResolverImpl()));
149 DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(DEFAULT_CACHE);
150 DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(
151 TextToASTTransformer.create(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY));
154 protected final String topologyId;
155 private final NetconfClientDispatcher clientDispatcher;
156 private final EventExecutor eventExecutor;
157 protected final ScheduledThreadPool keepaliveExecutor;
158 protected final ThreadPool processingExecutor;
159 protected final SharedSchemaRepository sharedSchemaRepository;
160 protected final DataBroker dataBroker;
161 protected final DOMMountPointService mountPointService;
163 protected SchemaSourceRegistry schemaRegistry = DEFAULT_SCHEMA_REPOSITORY;
164 protected SchemaRepository schemaRepository = DEFAULT_SCHEMA_REPOSITORY;
165 protected SchemaContextFactory schemaContextFactory = DEFAULT_SCHEMA_CONTEXT_FACTORY;
167 protected final HashMap<NodeId, NetconfConnectorDTO> activeConnectors = new HashMap<>();
169 protected AbstractNetconfTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
170 final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
171 final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider,
172 final DataBroker dataBroker, final DOMMountPointService mountPointService) {
173 this.topologyId = topologyId;
174 this.clientDispatcher = clientDispatcher;
175 this.eventExecutor = eventExecutor;
176 this.keepaliveExecutor = keepaliveExecutor;
177 this.processingExecutor = processingExecutor;
178 this.sharedSchemaRepository = schemaRepositoryProvider.getSharedSchemaRepository();
179 this.dataBroker = dataBroker;
180 this.mountPointService = mountPointService;
183 public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
184 this.schemaRegistry = schemaRegistry;
187 public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
188 this.schemaContextFactory = schemaContextFactory;
192 public ListenableFuture<NetconfDeviceCapabilities> connectNode(final NodeId nodeId, final Node configNode) {
193 LOG.info("Connecting RemoteDevice{{}} , with config {}", nodeId, configNode);
194 return setupConnection(nodeId, configNode);
198 public ListenableFuture<Void> disconnectNode(final NodeId nodeId) {
199 LOG.debug("Disconnecting RemoteDevice{{}}", nodeId.getValue());
200 if (!activeConnectors.containsKey(nodeId)) {
201 return Futures.immediateFailedFuture(new IllegalStateException("Unable to disconnect device that is not connected"));
204 // retrieve connection, and disconnect it
205 final NetconfConnectorDTO connectorDTO = activeConnectors.remove(nodeId);
206 connectorDTO.getCommunicator().close();
207 connectorDTO.getFacade().close();
208 return Futures.immediateFuture(null);
211 protected ListenableFuture<NetconfDeviceCapabilities> setupConnection(final NodeId nodeId,
212 final Node configNode) {
213 final NetconfNode netconfNode = configNode.getAugmentation(NetconfNode.class);
215 Preconditions.checkNotNull(netconfNode.getHost());
216 Preconditions.checkNotNull(netconfNode.getPort());
217 Preconditions.checkNotNull(netconfNode.isTcpOnly());
219 final NetconfConnectorDTO deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode);
220 final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
221 final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
222 final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(netconfClientSessionListener, netconfNode);
223 final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator.initializeRemoteConnection(clientDispatcher, clientConfig);
225 activeConnectors.put(nodeId, deviceCommunicatorDTO);
227 Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
229 public void onSuccess(final NetconfDeviceCapabilities result) {
230 LOG.debug("Connector for : " + nodeId.getValue() + " started succesfully");
234 public void onFailure(final Throwable t) {
235 LOG.error("Connector for : " + nodeId.getValue() + " failed");
236 // remove this node from active connectors?
243 protected NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId,
244 final NetconfNode node) {
245 //setup default values since default value is not supported in mdsal
246 final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null ? DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
247 final Long keepaliveDelay = node.getKeepaliveDelay() == null ? DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
248 final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null ? DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
250 final IpAddress ipAddress = node.getHost().getIpAddress();
251 final InetSocketAddress address = new InetSocketAddress(ipAddress.getIpv4Address() != null ?
252 ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue(),
253 node.getPort().getValue());
254 final RemoteDeviceId remoteDeviceId = new RemoteDeviceId(nodeId.getValue(), address);
256 RemoteDeviceHandler<NetconfSessionPreferences> salFacade =
257 createSalFacade(remoteDeviceId);
259 if (keepaliveDelay > 0) {
260 LOG.warn("Adding keepalive facade, for device {}", nodeId);
261 salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade, keepaliveExecutor.getExecutor(), keepaliveDelay, defaultRequestTimeoutMillis);
264 // pre register yang library sources as fallback schemas to schema registry
265 final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
266 if (node.getYangLibrary() != null) {
267 final String yangLibURL = node.getYangLibrary().getYangLibraryUrl().getValue();
268 final String yangLibUsername = node.getYangLibrary().getUsername();
269 final String yangLigPassword = node.getYangLibrary().getPassword();
271 final LibraryModulesSchemas libraryModulesSchemas;
272 if(yangLibURL != null) {
273 if(yangLibUsername != null && yangLigPassword != null) {
274 libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
276 libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
279 for (final Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry : libraryModulesSchemas.getAvailableModels().entrySet()) {
280 registeredYangLibSources.
281 add(schemaRegistry.registerSchemaSource(
282 new YangLibrarySchemaYangSourceProvider(remoteDeviceId, libraryModulesSchemas.getAvailableModels()),
283 PotentialSchemaSource
284 .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
285 PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
290 final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = setupSchemaCacheDTO(nodeId, node);
291 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device;
292 if (node.isSchemaless()) {
293 device = new SchemalessNetconfDevice(remoteDeviceId, salFacade);
295 device = new NetconfDeviceBuilder()
296 .setReconnectOnSchemasChange(reconnectOnChangedSchema)
297 .setSchemaResourcesDTO(schemaResourcesDTO)
298 .setGlobalProcessingExecutor(processingExecutor.getExecutor())
299 .setId(remoteDeviceId)
300 .setSalFacade(salFacade)
304 final Optional<UserPreferences> userCapabilities = getUserCapabilities(node);
305 final int rpcMessageLimit =
306 node.getConcurrentRpcLimit() == null ? DEFAULT_CONCURRENT_RPC_LIMIT : node.getConcurrentRpcLimit();
308 if (rpcMessageLimit < 1) {
309 LOG.info("Concurrent rpc limit is smaller than 1, no limit will be enforced for device {}", remoteDeviceId);
312 return new NetconfConnectorDTO(userCapabilities.isPresent()
313 ? new NetconfDeviceCommunicator(remoteDeviceId, device, userCapabilities.get(), rpcMessageLimit)
314 : new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit), salFacade);
317 protected NetconfDevice.SchemaResourcesDTO setupSchemaCacheDTO(final NodeId nodeId, final NetconfNode node) {
318 // Setup information related to the SchemaRegistry, SchemaResourceFactory, etc.
319 NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = null;
320 final String moduleSchemaCacheDirectory = node.getSchemaCacheDirectory();
321 // Only checks to ensure the String is not empty or null; further checks related to directory accessibility and file permissions
322 // are handled during the FilesystemSchemaSourceCache initialization.
323 if (!Strings.isNullOrEmpty(moduleSchemaCacheDirectory)) {
324 // If a custom schema cache directory is specified, create the backing DTO; otherwise, the SchemaRegistry and
325 // SchemaContextFactory remain the default values.
326 if (!moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
327 // Multiple modules may be created at once; synchronize to avoid issues with data consistency among threads.
328 synchronized(schemaResourcesDTOs) {
329 // Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables if they already exist
330 schemaResourcesDTO = schemaResourcesDTOs.get(moduleSchemaCacheDirectory);
331 if (schemaResourcesDTO == null) {
332 schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory);
333 schemaResourcesDTO.getSchemaRegistry().registerSchemaSourceListener(
334 TextToASTTransformer.create((SchemaRepository) schemaResourcesDTO.getSchemaRegistry(), schemaResourcesDTO.getSchemaRegistry())
336 schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
339 LOG.info("Netconf connector for device {} will use schema cache directory {} instead of {}",
340 nodeId.getValue(), moduleSchemaCacheDirectory, DEFAULT_CACHE_DIRECTORY);
343 LOG.warn("schema-cache-directory for {} is null or empty; using the default {}",
344 nodeId.getValue(), QUALIFIED_DEFAULT_CACHE_DIRECTORY);
347 if (schemaResourcesDTO == null) {
348 schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaRepository, schemaContextFactory,
349 new NetconfStateSchemasResolverImpl());
352 return schemaResourcesDTO;
356 * Creates the backing Schema classes for a particular directory.
358 * @param moduleSchemaCacheDirectory The string directory relative to "cache"
359 * @return A DTO containing the Schema classes for the Netconf mount.
361 private NetconfDevice.SchemaResourcesDTO createSchemaResourcesDTO(final String moduleSchemaCacheDirectory) {
362 final SharedSchemaRepository repository = new SharedSchemaRepository(moduleSchemaCacheDirectory);
363 final SchemaContextFactory schemaContextFactory
364 = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
365 setSchemaRegistry(repository);
366 setSchemaContextFactory(schemaContextFactory);
367 final FilesystemSchemaSourceCache<YangTextSchemaSource> deviceCache =
368 createDeviceFilesystemCache(moduleSchemaCacheDirectory);
369 repository.registerSchemaSourceListener(deviceCache);
370 return new NetconfDevice.SchemaResourcesDTO(repository, repository, schemaContextFactory,
371 new NetconfStateSchemasResolverImpl());
375 * Creates a <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory.
377 * @param schemaCacheDirectory The custom cache directory relative to "cache"
378 * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
380 private FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(final String schemaCacheDirectory) {
381 final String relativeSchemaCacheDirectory = CACHE_DIRECTORY + File.separator + schemaCacheDirectory;
382 return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class, new File(relativeSchemaCacheDirectory));
385 public NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener, final NetconfNode node) {
387 //setup default values since default value is not supported in mdsal
388 final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null ? DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
389 final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null ? DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
390 final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null ? DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
391 final BigDecimal sleepFactor = node.getSleepFactor() == null ? DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
393 final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
395 final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
396 maxConnectionAttempts, betweenAttemptsTimeoutMillis, sleepFactor);
397 final ReconnectStrategy strategy = sf.createReconnectStrategy();
399 final AuthenticationHandler authHandler;
400 final Credentials credentials = node.getCredentials();
401 if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) {
402 authHandler = new LoginPassword(
403 ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getUsername(),
404 ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getPassword());
406 throw new IllegalStateException("Only login/password authentification is supported");
409 return NetconfReconnectingClientConfigurationBuilder.create()
410 .withAddress(socketAddress)
411 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
412 .withReconnectStrategy(strategy)
413 .withAuthHandler(authHandler)
414 .withProtocol(node.isTcpOnly() ?
415 NetconfClientConfiguration.NetconfClientProtocol.TCP :
416 NetconfClientConfiguration.NetconfClientProtocol.SSH)
417 .withConnectStrategyFactory(sf)
418 .withSessionListener(listener)
422 protected abstract RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id);
424 private InetSocketAddress getSocketAddress(final Host host, final int port) {
425 if(host.getDomainName() != null) {
426 return new InetSocketAddress(host.getDomainName().getValue(), port);
428 final IpAddress ipAddress = host.getIpAddress();
429 final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
430 return new InetSocketAddress(ip, port);
434 private Optional<UserPreferences> getUserCapabilities(final NetconfNode node) {
435 // if none of yang-module-capabilities or non-module-capabilities is specified
436 // just return absent
437 if (node.getYangModuleCapabilities() == null && node.getNonModuleCapabilities() == null) {
438 return Optional.absent();
441 final List<String> capabilities = new ArrayList<>();
443 boolean overrideYangModuleCaps = false;
444 if (node.getYangModuleCapabilities() != null) {
445 capabilities.addAll(node.getYangModuleCapabilities().getCapability());
446 overrideYangModuleCaps = node.getYangModuleCapabilities().isOverride();
449 //non-module capabilities should not exist in yang module capabilities
450 final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(capabilities);
451 Preconditions.checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(), "List yang-module-capabilities/capability " +
452 "should contain only module based capabilities. Non-module capabilities used: " +
453 netconfSessionPreferences.getNonModuleCaps());
455 boolean overrideNonModuleCaps = false;
456 if (node.getNonModuleCapabilities() != null) {
457 capabilities.addAll(node.getNonModuleCapabilities().getCapability());
458 overrideNonModuleCaps = node.getNonModuleCapabilities().isOverride();
461 return Optional.of(new UserPreferences(NetconfSessionPreferences.fromStrings(capabilities, CapabilityOrigin.UserDefined),
462 overrideYangModuleCaps, overrideNonModuleCaps));
465 private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
466 private final Long connectionAttempts;
467 private final EventExecutor executor;
468 private final double sleepFactor;
469 private final int minSleep;
471 TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
472 if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
473 connectionAttempts = maxConnectionAttempts;
475 connectionAttempts = null;
478 this.sleepFactor = sleepFactor.doubleValue();
479 this.executor = executor;
480 this.minSleep = minSleep;
484 public ReconnectStrategy createReconnectStrategy() {
485 final Long maxSleep = null;
486 final Long deadline = null;
488 return new TimedReconnectStrategy(executor, minSleep,
489 minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
493 protected static class NetconfConnectorDTO implements AutoCloseable {
495 private final NetconfDeviceCommunicator communicator;
496 private final RemoteDeviceHandler<NetconfSessionPreferences> facade;
498 public NetconfConnectorDTO(final NetconfDeviceCommunicator communicator, final RemoteDeviceHandler<NetconfSessionPreferences> facade) {
499 this.communicator = communicator;
500 this.facade = facade;
503 public NetconfDeviceCommunicator getCommunicator() {
507 public RemoteDeviceHandler<NetconfSessionPreferences> getFacade() {
511 public NetconfClientSessionListener getSessionListener() {
516 public void close() {
517 communicator.close();