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