Bug 4940 - correctly implement default-request-timeout-millis
[netconf.git] / netconf / netconf-topology / src / main / java / org / opendaylight / netconf / topology / AbstractNetconfTopology.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.netconf.topology;
10
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.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import io.netty.util.concurrent.EventExecutor;
18 import java.io.File;
19 import java.math.BigDecimal;
20 import java.net.InetSocketAddress;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
27 import org.opendaylight.controller.config.threadpool.ThreadPool;
28 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
29 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
30 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
31 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
32 import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
33 import org.opendaylight.controller.sal.core.api.Broker;
34 import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
35 import org.opendaylight.controller.sal.core.api.Provider;
36 import org.opendaylight.netconf.client.NetconfClientDispatcher;
37 import org.opendaylight.netconf.client.NetconfClientSessionListener;
38 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
39 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
40 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
41 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
42 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
43 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
44 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
45 import org.opendaylight.netconf.sal.connect.netconf.NetconfStateSchemas;
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.util.RemoteDeviceId;
52 import org.opendaylight.netconf.topology.pipeline.TopologyMountPointFacade.ConnectionStatusListenerRegistration;
53 import org.opendaylight.protocol.framework.ReconnectStrategy;
54 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
55 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
60 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
61 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
64 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
65 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
66 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
67 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
68 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
69 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72
73 public abstract class AbstractNetconfTopology implements NetconfTopology, BindingAwareProvider, Provider {
74
75     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfTopology.class);
76
77     protected static final long DEFAULT_REQUEST_TIMEOUT_MILLIS = 60000L;
78     protected static final int DEFAULT_KEEPALIVE_DELAY = 0;
79     protected static final boolean DEFAULT_RECONNECT_ON_CHANGED_SCHEMA = false;
80     private static final int DEFAULT_MAX_CONNECTION_ATTEMPTS = 0;
81     private static final int DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS = 2000;
82     private static final long DEFAULT_CONNECTION_TIMEOUT_MILLIS = 20000L;
83     private static final BigDecimal DEFAULT_SLEEP_FACTOR = new BigDecimal(1.5);
84
85     // constants related to Schema Cache(s)
86     /**
87      * Filesystem based caches are stored relative to the cache directory.
88      */
89     private static final String CACHE_DIRECTORY = "cache";
90
91     /**
92      * The default cache directory relative to <code>CACHE_DIRECTORY</code>
93      */
94     private static final String DEFAULT_CACHE_DIRECTORY = "schema";
95
96     /**
97      * The qualified schema cache directory <code>cache/schema</code>
98      */
99     private static final String QUALIFIED_DEFAULT_CACHE_DIRECTORY = CACHE_DIRECTORY + File.separator+ DEFAULT_CACHE_DIRECTORY;
100
101     /**
102      * The name for the default schema repository
103      */
104     private static final String DEFAULT_SCHEMA_REPOSITORY_NAME = "sal-netconf-connector";
105
106     /**
107      * The default schema repository in the case that one is not specified.
108      */
109     private static final SharedSchemaRepository DEFAULT_SCHEMA_REPOSITORY =
110             new SharedSchemaRepository(DEFAULT_SCHEMA_REPOSITORY_NAME);
111
112     /**
113      * The default <code>FilesystemSchemaSourceCache</code>, which stores cached files in <code>cache/schema</code>.
114      */
115     private static final FilesystemSchemaSourceCache<YangTextSchemaSource> DEFAULT_CACHE =
116             new FilesystemSchemaSourceCache<>(DEFAULT_SCHEMA_REPOSITORY, YangTextSchemaSource.class,
117                     new File(QUALIFIED_DEFAULT_CACHE_DIRECTORY));
118
119     /**
120      * The default factory for creating <code>SchemaContext</code> instances.
121      */
122     private static final SchemaContextFactory DEFAULT_SCHEMA_CONTEXT_FACTORY =
123             DEFAULT_SCHEMA_REPOSITORY.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
124
125     /**
126      * Keeps track of initialized Schema resources.  A Map is maintained in which the key represents the name
127      * of the schema cache directory, and the value is a corresponding <code>SchemaResourcesDTO</code>.  The
128      * <code>SchemaResourcesDTO</code> is essentially a container that allows for the extraction of the
129      * <code>SchemaRegistry</code> and <code>SchemaContextFactory</code> which should be used for a particular
130      * Netconf mount.  Access to <code>schemaResourcesDTOs</code> should be surrounded by appropriate
131      * synchronization locks.
132      */
133     private static volatile Map<String, NetconfDevice.SchemaResourcesDTO> schemaResourcesDTOs = new HashMap<>();
134
135     // Initializes default constant instances for the case when the default schema repository
136     // directory cache/schema is used.
137     static {
138         schemaResourcesDTOs.put(DEFAULT_CACHE_DIRECTORY,
139                 new NetconfDevice.SchemaResourcesDTO(DEFAULT_SCHEMA_REPOSITORY,
140                         DEFAULT_SCHEMA_CONTEXT_FACTORY,
141                         new NetconfStateSchemas.NetconfStateSchemasResolverImpl()));
142         DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(DEFAULT_CACHE);
143         DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(
144                 TextToASTTransformer.create(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY));
145     }
146
147     protected final String topologyId;
148     private final NetconfClientDispatcher clientDispatcher;
149     protected final BindingAwareBroker bindingAwareBroker;
150     protected final Broker domBroker;
151     private final EventExecutor eventExecutor;
152     protected final ScheduledThreadPool keepaliveExecutor;
153     protected final ThreadPool processingExecutor;
154     protected final SharedSchemaRepository sharedSchemaRepository;
155
156     protected SchemaSourceRegistry schemaRegistry = DEFAULT_SCHEMA_REPOSITORY;
157     protected SchemaContextFactory schemaContextFactory = DEFAULT_SCHEMA_CONTEXT_FACTORY;
158
159     protected DOMMountPointService mountPointService = null;
160     protected DataBroker dataBroker = null;
161     protected final HashMap<NodeId, NetconfConnectorDTO> activeConnectors = new HashMap<>();
162
163     protected AbstractNetconfTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
164                                       final BindingAwareBroker bindingAwareBroker, final Broker domBroker,
165                                       final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
166                                       final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider) {
167         this.topologyId = topologyId;
168         this.clientDispatcher = clientDispatcher;
169         this.bindingAwareBroker = bindingAwareBroker;
170         this.domBroker = domBroker;
171         this.eventExecutor = eventExecutor;
172         this.keepaliveExecutor = keepaliveExecutor;
173         this.processingExecutor = processingExecutor;
174         this.sharedSchemaRepository = schemaRepositoryProvider.getSharedSchemaRepository();
175     }
176
177     protected void registerToSal(BindingAwareProvider baProvider, Provider provider) {
178         domBroker.registerProvider(provider);
179         bindingAwareBroker.registerProvider(baProvider);
180     }
181
182     public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
183         this.schemaRegistry = schemaRegistry;
184     }
185
186     public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
187         this.schemaContextFactory = schemaContextFactory;
188     }
189
190     @Override
191     public abstract void onSessionInitiated(ProviderContext session);
192
193     @Override
194     public String getTopologyId() {
195         return topologyId;
196     }
197
198     @Override
199     public DataBroker getDataBroker() {
200         return dataBroker;
201     }
202
203     @Override
204     public ListenableFuture<NetconfDeviceCapabilities> connectNode(NodeId nodeId, Node configNode) {
205         LOG.info("Connecting RemoteDevice{{}} , with config {}", nodeId, configNode);
206         return setupConnection(nodeId, configNode);
207     }
208
209     @Override
210     public ListenableFuture<Void> disconnectNode(NodeId nodeId) {
211         LOG.debug("Disconnecting RemoteDevice{{}}", nodeId.getValue());
212         if (!activeConnectors.containsKey(nodeId)) {
213             return Futures.immediateFailedFuture(new IllegalStateException("Unable to disconnect device that is not connected"));
214         }
215
216         // retrieve connection, and disconnect it
217         final NetconfConnectorDTO connectorDTO = activeConnectors.remove(nodeId);
218         connectorDTO.getCommunicator().close();
219         connectorDTO.getFacade().close();
220         return Futures.immediateFuture(null);
221     }
222
223     protected ListenableFuture<NetconfDeviceCapabilities> setupConnection(final NodeId nodeId,
224                                                                         final Node configNode) {
225         final NetconfNode netconfNode = configNode.getAugmentation(NetconfNode.class);
226
227         Preconditions.checkNotNull(netconfNode.getHost());
228         Preconditions.checkNotNull(netconfNode.getPort());
229         Preconditions.checkNotNull(netconfNode.isTcpOnly());
230
231         final NetconfConnectorDTO deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode);
232         final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
233         final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
234         final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(netconfClientSessionListener, netconfNode);
235         final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator.initializeRemoteConnection(clientDispatcher, clientConfig);
236
237         activeConnectors.put(nodeId, deviceCommunicatorDTO);
238
239         Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
240             @Override
241             public void onSuccess(NetconfDeviceCapabilities result) {
242                 LOG.debug("Connector for : " + nodeId.getValue() + " started succesfully");
243             }
244
245             @Override
246             public void onFailure(Throwable t) {
247                 LOG.error("Connector for : " + nodeId.getValue() + " failed");
248                 // remove this node from active connectors?
249             }
250         });
251
252         return future;
253     }
254
255     protected NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId,
256                                                          final NetconfNode node) {
257         //setup default values since default value is not supported in mdsal
258         final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null ? DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
259         final Long keepaliveDelay = node.getKeepaliveDelay() == null ? DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
260         final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null ? DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
261
262         IpAddress ipAddress = node.getHost().getIpAddress();
263         InetSocketAddress address = new InetSocketAddress(ipAddress.getIpv4Address() != null ?
264                 ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue(),
265                 node.getPort().getValue());
266         RemoteDeviceId remoteDeviceId = new RemoteDeviceId(nodeId.getValue(), address);
267
268         RemoteDeviceHandler<NetconfSessionPreferences> salFacade =
269                 createSalFacade(remoteDeviceId, domBroker, bindingAwareBroker);
270
271         if (keepaliveDelay > 0) {
272             LOG.warn("Adding keepalive facade, for device {}", nodeId);
273             salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade, keepaliveExecutor.getExecutor(), keepaliveDelay, defaultRequestTimeoutMillis);
274         }
275
276         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = setupSchemaCacheDTO(nodeId, node);
277
278         final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, remoteDeviceId, salFacade,
279                 processingExecutor.getExecutor(), reconnectOnChangedSchema);
280
281         final Optional<NetconfSessionPreferences> userCapabilities = getUserCapabilities(node);
282
283         return new NetconfConnectorDTO(
284                 userCapabilities.isPresent() ?
285                         new NetconfDeviceCommunicator(
286                                 remoteDeviceId, device, new UserPreferences(userCapabilities.get(), node.getYangModuleCapabilities().isOverride())):
287                         new NetconfDeviceCommunicator(remoteDeviceId, device)
288                 , salFacade);
289     }
290
291     protected NetconfDevice.SchemaResourcesDTO setupSchemaCacheDTO(final NodeId nodeId, final NetconfNode node) {
292         // Setup information related to the SchemaRegistry, SchemaResourceFactory, etc.
293         NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = null;
294         final String moduleSchemaCacheDirectory = node.getSchemaCacheDirectory();
295         // Only checks to ensure the String is not empty or null;  further checks related to directory accessibility and file permissions
296         // are handled during the FilesystemSchemaSourceCache initialization.
297         if (!Strings.isNullOrEmpty(moduleSchemaCacheDirectory)) {
298             // If a custom schema cache directory is specified, create the backing DTO; otherwise, the SchemaRegistry and
299             // SchemaContextFactory remain the default values.
300             if (!moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
301                 // Multiple modules may be created at once;  synchronize to avoid issues with data consistency among threads.
302                 synchronized(schemaResourcesDTOs) {
303                     // Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables if they already exist
304                     schemaResourcesDTO = schemaResourcesDTOs.get(moduleSchemaCacheDirectory);
305                     if (schemaResourcesDTO == null) {
306                         schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory);
307                         schemaResourcesDTO.getSchemaRegistry().registerSchemaSourceListener(
308                                 TextToASTTransformer.create((SchemaRepository) schemaResourcesDTO.getSchemaRegistry(), schemaResourcesDTO.getSchemaRegistry())
309                         );
310                         schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
311                     }
312                 }
313                 LOG.info("Netconf connector for device {} will use schema cache directory {} instead of {}",
314                         nodeId.getValue(), moduleSchemaCacheDirectory, DEFAULT_CACHE_DIRECTORY);
315             }
316         } else {
317             LOG.warn("schema-cache-directory for {} is null or empty;  using the default {}",
318                     nodeId.getValue(), QUALIFIED_DEFAULT_CACHE_DIRECTORY);
319         }
320
321         if (schemaResourcesDTO == null) {
322             schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaContextFactory,
323                     new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
324         }
325
326         return schemaResourcesDTO;
327     }
328
329     /**
330      * Creates the backing Schema classes for a particular directory.
331      *
332      * @param moduleSchemaCacheDirectory The string directory relative to "cache"
333      * @return A DTO containing the Schema classes for the Netconf mount.
334      */
335     private NetconfDevice.SchemaResourcesDTO createSchemaResourcesDTO(final String moduleSchemaCacheDirectory) {
336         final SharedSchemaRepository repository = new SharedSchemaRepository(moduleSchemaCacheDirectory);
337         final SchemaContextFactory schemaContextFactory
338                 = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
339         setSchemaRegistry(repository);
340         setSchemaContextFactory(schemaContextFactory);
341         final FilesystemSchemaSourceCache<YangTextSchemaSource> deviceCache =
342                 createDeviceFilesystemCache(moduleSchemaCacheDirectory);
343         repository.registerSchemaSourceListener(deviceCache);
344         return new NetconfDevice.SchemaResourcesDTO(repository, schemaContextFactory,
345                 new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
346     }
347
348     /**
349      * Creates a <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory.
350      *
351      * @param schemaCacheDirectory The custom cache directory relative to "cache"
352      * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
353      */
354     private FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(final String schemaCacheDirectory) {
355         final String relativeSchemaCacheDirectory = CACHE_DIRECTORY + File.separator + schemaCacheDirectory;
356         return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class, new File(relativeSchemaCacheDirectory));
357     }
358
359     public NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener, NetconfNode node) {
360
361         //setup default values since default value is not supported in mdsal
362         final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null ? DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
363         final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null ? DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
364         final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null ? DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
365         final BigDecimal sleepFactor = node.getSleepFactor() == null ? DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
366
367         final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
368
369         final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
370                 maxConnectionAttempts, betweenAttemptsTimeoutMillis, sleepFactor);
371         final ReconnectStrategy strategy = sf.createReconnectStrategy();
372
373         final AuthenticationHandler authHandler;
374         final Credentials credentials = node.getCredentials();
375         if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) {
376             authHandler = new LoginPassword(
377                     ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getUsername(),
378                     ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getPassword());
379         } else {
380             throw new IllegalStateException("Only login/password authentification is supported");
381         }
382
383         return NetconfReconnectingClientConfigurationBuilder.create()
384                 .withAddress(socketAddress)
385                 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
386                 .withReconnectStrategy(strategy)
387                 .withAuthHandler(authHandler)
388                 .withProtocol(node.isTcpOnly() ?
389                         NetconfClientConfiguration.NetconfClientProtocol.TCP :
390                         NetconfClientConfiguration.NetconfClientProtocol.SSH)
391                 .withConnectStrategyFactory(sf)
392                 .withSessionListener(listener)
393                 .build();
394     }
395
396     protected abstract RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id, final Broker domBroker, final BindingAwareBroker bindingBroker);
397
398     @Override
399     public abstract ConnectionStatusListenerRegistration registerConnectionStatusListener(NodeId node, RemoteDeviceHandler<NetconfSessionPreferences> listener);
400
401     @Override
402     public void onSessionInitiated(ProviderSession session) {
403          mountPointService = session.getService(DOMMountPointService.class);
404     }
405
406     @Override
407     public Collection<ProviderFunctionality> getProviderFunctionality() {
408         return Collections.emptySet();
409     }
410
411     private InetSocketAddress getSocketAddress(final Host host, int port) {
412         if(host.getDomainName() != null) {
413             return new InetSocketAddress(host.getDomainName().getValue(), port);
414         } else {
415             final IpAddress ipAddress = host.getIpAddress();
416             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
417             return new InetSocketAddress(ip, port);
418         }
419     }
420
421     private Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
422         if(node.getYangModuleCapabilities() == null) {
423             return Optional.absent();
424         }
425
426         final List<String> capabilities = node.getYangModuleCapabilities().getCapability();
427         if(capabilities == null || capabilities.isEmpty()) {
428             return Optional.absent();
429         }
430
431         final NetconfSessionPreferences parsedOverrideCapabilities = NetconfSessionPreferences.fromStrings(capabilities);
432         Preconditions.checkState(parsedOverrideCapabilities.getNonModuleCaps().isEmpty(), "Capabilities to override can " +
433                 "only contain module based capabilities, non-module capabilities will be retrieved from the device," +
434                 " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps());
435
436         return Optional.of(parsedOverrideCapabilities);
437     }
438
439     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
440         private final Long connectionAttempts;
441         private final EventExecutor executor;
442         private final double sleepFactor;
443         private final int minSleep;
444
445         TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
446             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
447                 connectionAttempts = maxConnectionAttempts;
448             } else {
449                 connectionAttempts = null;
450             }
451
452             this.sleepFactor = sleepFactor.doubleValue();
453             this.executor = executor;
454             this.minSleep = minSleep;
455         }
456
457         @Override
458         public ReconnectStrategy createReconnectStrategy() {
459             final Long maxSleep = null;
460             final Long deadline = null;
461
462             return new TimedReconnectStrategy(executor, minSleep,
463                     minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
464         }
465     }
466
467     protected static class NetconfConnectorDTO {
468
469         private final NetconfDeviceCommunicator communicator;
470         private final RemoteDeviceHandler<NetconfSessionPreferences> facade;
471
472         public NetconfConnectorDTO(final NetconfDeviceCommunicator communicator, final RemoteDeviceHandler<NetconfSessionPreferences> facade) {
473             this.communicator = communicator;
474             this.facade = facade;
475         }
476
477         public NetconfDeviceCommunicator getCommunicator() {
478             return communicator;
479         }
480
481         public RemoteDeviceHandler<NetconfSessionPreferences> getFacade() {
482             return facade;
483         }
484
485         public NetconfClientSessionListener getSessionListener() {
486             return communicator;
487         }
488     }
489
490 }