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