Bug 6198 - Use sal-netconf-connector to connet device costs too much time
[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.netconf.topology.pipeline.TopologyMountPointFacade.ConnectionStatusListenerRegistration;
61 import org.opendaylight.protocol.framework.ReconnectStrategy;
62 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
63 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
64 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
65 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
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 String getTopologyId() {
208         return topologyId;
209     }
210
211     @Override
212     public DataBroker getDataBroker() {
213         return dataBroker;
214     }
215
216     @Override
217     public ListenableFuture<NetconfDeviceCapabilities> connectNode(NodeId nodeId, Node configNode) {
218         LOG.info("Connecting RemoteDevice{{}} , with config {}", nodeId, configNode);
219         return setupConnection(nodeId, configNode);
220     }
221
222     @Override
223     public ListenableFuture<Void> disconnectNode(NodeId nodeId) {
224         LOG.debug("Disconnecting RemoteDevice{{}}", nodeId.getValue());
225         if (!activeConnectors.containsKey(nodeId)) {
226             return Futures.immediateFailedFuture(new IllegalStateException("Unable to disconnect device that is not connected"));
227         }
228
229         // retrieve connection, and disconnect it
230         final NetconfConnectorDTO connectorDTO = activeConnectors.remove(nodeId);
231         connectorDTO.getCommunicator().close();
232         connectorDTO.getFacade().close();
233         return Futures.immediateFuture(null);
234     }
235
236     protected ListenableFuture<NetconfDeviceCapabilities> setupConnection(final NodeId nodeId,
237                                                                         final Node configNode) {
238         final NetconfNode netconfNode = configNode.getAugmentation(NetconfNode.class);
239
240         Preconditions.checkNotNull(netconfNode.getHost());
241         Preconditions.checkNotNull(netconfNode.getPort());
242         Preconditions.checkNotNull(netconfNode.isTcpOnly());
243
244         final NetconfConnectorDTO deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode);
245         final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
246         final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
247         final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(netconfClientSessionListener, netconfNode);
248         final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator.initializeRemoteConnection(clientDispatcher, clientConfig);
249
250         activeConnectors.put(nodeId, deviceCommunicatorDTO);
251
252         Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
253             @Override
254             public void onSuccess(NetconfDeviceCapabilities result) {
255                 LOG.debug("Connector for : " + nodeId.getValue() + " started succesfully");
256             }
257
258             @Override
259             public void onFailure(Throwable t) {
260                 LOG.error("Connector for : " + nodeId.getValue() + " failed");
261                 // remove this node from active connectors?
262             }
263         });
264
265         return future;
266     }
267
268     protected NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId,
269                                                          final NetconfNode node) {
270         //setup default values since default value is not supported in mdsal
271         final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null ? DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
272         final Long keepaliveDelay = node.getKeepaliveDelay() == null ? DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
273         final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null ? DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
274
275         IpAddress ipAddress = node.getHost().getIpAddress();
276         InetSocketAddress address = new InetSocketAddress(ipAddress.getIpv4Address() != null ?
277                 ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue(),
278                 node.getPort().getValue());
279         RemoteDeviceId remoteDeviceId = new RemoteDeviceId(nodeId.getValue(), address);
280
281         RemoteDeviceHandler<NetconfSessionPreferences> salFacade =
282                 createSalFacade(remoteDeviceId, domBroker, bindingAwareBroker);
283
284         if (keepaliveDelay > 0) {
285             LOG.warn("Adding keepalive facade, for device {}", nodeId);
286             salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade, keepaliveExecutor.getExecutor(), keepaliveDelay, defaultRequestTimeoutMillis);
287         }
288
289         // pre register yang library sources as fallback schemas to schema registry
290         List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
291         if (node.getYangLibrary() != null) {
292             final String yangLibURL = node.getYangLibrary().getYangLibraryUrl().getValue();
293             final String yangLibUsername = node.getYangLibrary().getUsername();
294             final String yangLigPassword = node.getYangLibrary().getPassword();
295
296             LibraryModulesSchemas libraryModulesSchemas;
297             if(yangLibURL != null) {
298                 if(yangLibUsername != null && yangLigPassword != null) {
299                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
300                 } else {
301                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
302                 }
303
304                 for (Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry : libraryModulesSchemas.getAvailableModels().entrySet()) {
305                     registeredYangLibSources.
306                             add(schemaRegistry.registerSchemaSource(
307                                     new YangLibrarySchemaYangSourceProvider(remoteDeviceId, libraryModulesSchemas.getAvailableModels()),
308                                     PotentialSchemaSource
309                                             .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
310                                             PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
311                 }
312             }
313         }
314
315         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = setupSchemaCacheDTO(nodeId, node);
316         final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device;
317         if (node.isSchemaless()) {
318             device = new SchemalessNetconfDevice(remoteDeviceId, salFacade);
319         } else {
320             device = new NetconfDeviceBuilder()
321                     .setReconnectOnSchemasChange(reconnectOnChangedSchema)
322                     .setSchemaResourcesDTO(schemaResourcesDTO)
323                     .setGlobalProcessingExecutor(processingExecutor.getExecutor())
324                     .setId(remoteDeviceId)
325                     .setSalFacade(salFacade)
326                     .build();
327         }
328
329         final Optional<NetconfSessionPreferences> userCapabilities = getUserCapabilities(node);
330         final int rpcMessageLimit =
331                 node.getConcurrentRpcLimit() == null ? DEFAULT_CONCURRENT_RPC_LIMIT : node.getConcurrentRpcLimit();
332
333         if (rpcMessageLimit < 1) {
334             LOG.info("Concurrent rpc limit is smaller than 1, no limit will be enforced for device {}", remoteDeviceId);
335         }
336
337         return new NetconfConnectorDTO(
338                 userCapabilities.isPresent() ?
339                         new NetconfDeviceCommunicator(
340                                 remoteDeviceId, device, new UserPreferences(userCapabilities.get(), node.getYangModuleCapabilities().isOverride()), rpcMessageLimit):
341                         new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit), salFacade);
342     }
343
344     protected NetconfDevice.SchemaResourcesDTO setupSchemaCacheDTO(final NodeId nodeId, final NetconfNode node) {
345         // Setup information related to the SchemaRegistry, SchemaResourceFactory, etc.
346         NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = null;
347         final String moduleSchemaCacheDirectory = node.getSchemaCacheDirectory();
348         // Only checks to ensure the String is not empty or null;  further checks related to directory accessibility and file permissions
349         // are handled during the FilesystemSchemaSourceCache initialization.
350         if (!Strings.isNullOrEmpty(moduleSchemaCacheDirectory)) {
351             // If a custom schema cache directory is specified, create the backing DTO; otherwise, the SchemaRegistry and
352             // SchemaContextFactory remain the default values.
353             if (!moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
354                 // Multiple modules may be created at once;  synchronize to avoid issues with data consistency among threads.
355                 synchronized(schemaResourcesDTOs) {
356                     // Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables if they already exist
357                     schemaResourcesDTO = schemaResourcesDTOs.get(moduleSchemaCacheDirectory);
358                     if (schemaResourcesDTO == null) {
359                         schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory);
360                         schemaResourcesDTO.getSchemaRegistry().registerSchemaSourceListener(
361                                 TextToASTTransformer.create((SchemaRepository) schemaResourcesDTO.getSchemaRegistry(), schemaResourcesDTO.getSchemaRegistry())
362                         );
363                         schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
364                     }
365                 }
366                 LOG.info("Netconf connector for device {} will use schema cache directory {} instead of {}",
367                         nodeId.getValue(), moduleSchemaCacheDirectory, DEFAULT_CACHE_DIRECTORY);
368             }
369         } else {
370             LOG.warn("schema-cache-directory for {} is null or empty;  using the default {}",
371                     nodeId.getValue(), QUALIFIED_DEFAULT_CACHE_DIRECTORY);
372         }
373
374         if (schemaResourcesDTO == null) {
375             schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaRepository, schemaContextFactory,
376                     new NetconfStateSchemasResolverImpl());
377         }
378
379         return schemaResourcesDTO;
380     }
381
382     /**
383      * Creates the backing Schema classes for a particular directory.
384      *
385      * @param moduleSchemaCacheDirectory The string directory relative to "cache"
386      * @return A DTO containing the Schema classes for the Netconf mount.
387      */
388     private NetconfDevice.SchemaResourcesDTO createSchemaResourcesDTO(final String moduleSchemaCacheDirectory) {
389         final SharedSchemaRepository repository = new SharedSchemaRepository(moduleSchemaCacheDirectory);
390         final SchemaContextFactory schemaContextFactory
391                 = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
392         setSchemaRegistry(repository);
393         setSchemaContextFactory(schemaContextFactory);
394         final FilesystemSchemaSourceCache<YangTextSchemaSource> deviceCache =
395                 createDeviceFilesystemCache(moduleSchemaCacheDirectory);
396         repository.registerSchemaSourceListener(deviceCache);
397         return new NetconfDevice.SchemaResourcesDTO(repository, repository, schemaContextFactory,
398                 new NetconfStateSchemasResolverImpl());
399     }
400
401     /**
402      * Creates a <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory.
403      *
404      * @param schemaCacheDirectory The custom cache directory relative to "cache"
405      * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
406      */
407     private FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(final String schemaCacheDirectory) {
408         final String relativeSchemaCacheDirectory = CACHE_DIRECTORY + File.separator + schemaCacheDirectory;
409         return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class, new File(relativeSchemaCacheDirectory));
410     }
411
412     public NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener, NetconfNode node) {
413
414         //setup default values since default value is not supported in mdsal
415         final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null ? DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
416         final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null ? DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
417         final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null ? DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
418         final BigDecimal sleepFactor = node.getSleepFactor() == null ? DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
419
420         final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
421
422         final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
423                 maxConnectionAttempts, betweenAttemptsTimeoutMillis, sleepFactor);
424         final ReconnectStrategy strategy = sf.createReconnectStrategy();
425
426         final AuthenticationHandler authHandler;
427         final Credentials credentials = node.getCredentials();
428         if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) {
429             authHandler = new LoginPassword(
430                     ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getUsername(),
431                     ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getPassword());
432         } else {
433             throw new IllegalStateException("Only login/password authentification is supported");
434         }
435
436         return NetconfReconnectingClientConfigurationBuilder.create()
437                 .withAddress(socketAddress)
438                 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
439                 .withReconnectStrategy(strategy)
440                 .withAuthHandler(authHandler)
441                 .withProtocol(node.isTcpOnly() ?
442                         NetconfClientConfiguration.NetconfClientProtocol.TCP :
443                         NetconfClientConfiguration.NetconfClientProtocol.SSH)
444                 .withConnectStrategyFactory(sf)
445                 .withSessionListener(listener)
446                 .build();
447     }
448
449     protected abstract RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id, final Broker domBroker, final BindingAwareBroker bindingBroker);
450
451     @Override
452     public abstract ConnectionStatusListenerRegistration registerConnectionStatusListener(NodeId node, RemoteDeviceHandler<NetconfSessionPreferences> listener);
453
454     @Override
455     public void onSessionInitiated(ProviderSession session) {
456          mountPointService = session.getService(DOMMountPointService.class);
457     }
458
459     @Override
460     public Collection<ProviderFunctionality> getProviderFunctionality() {
461         return Collections.emptySet();
462     }
463
464     private InetSocketAddress getSocketAddress(final Host host, int port) {
465         if(host.getDomainName() != null) {
466             return new InetSocketAddress(host.getDomainName().getValue(), port);
467         } else {
468             final IpAddress ipAddress = host.getIpAddress();
469             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
470             return new InetSocketAddress(ip, port);
471         }
472     }
473
474     private Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
475         if(node.getYangModuleCapabilities() == null) {
476             return Optional.absent();
477         }
478
479         final List<String> capabilities = node.getYangModuleCapabilities().getCapability();
480         if(capabilities == null || capabilities.isEmpty()) {
481             return Optional.absent();
482         }
483
484         final NetconfSessionPreferences parsedOverrideCapabilities = NetconfSessionPreferences.fromStrings(capabilities);
485         Preconditions.checkState(parsedOverrideCapabilities.getNonModuleCaps().isEmpty(), "Capabilities to override can " +
486                 "only contain module based capabilities, non-module capabilities will be retrieved from the device," +
487                 " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps());
488
489         return Optional.of(parsedOverrideCapabilities);
490     }
491
492     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
493         private final Long connectionAttempts;
494         private final EventExecutor executor;
495         private final double sleepFactor;
496         private final int minSleep;
497
498         TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
499             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
500                 connectionAttempts = maxConnectionAttempts;
501             } else {
502                 connectionAttempts = null;
503             }
504
505             this.sleepFactor = sleepFactor.doubleValue();
506             this.executor = executor;
507             this.minSleep = minSleep;
508         }
509
510         @Override
511         public ReconnectStrategy createReconnectStrategy() {
512             final Long maxSleep = null;
513             final Long deadline = null;
514
515             return new TimedReconnectStrategy(executor, minSleep,
516                     minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
517         }
518     }
519
520     protected static class NetconfConnectorDTO {
521
522         private final NetconfDeviceCommunicator communicator;
523         private final RemoteDeviceHandler<NetconfSessionPreferences> facade;
524
525         public NetconfConnectorDTO(final NetconfDeviceCommunicator communicator, final RemoteDeviceHandler<NetconfSessionPreferences> facade) {
526             this.communicator = communicator;
527             this.facade = facade;
528         }
529
530         public NetconfDeviceCommunicator getCommunicator() {
531             return communicator;
532         }
533
534         public RemoteDeviceHandler<NetconfSessionPreferences> getFacade() {
535             return facade;
536         }
537
538         public NetconfClientSessionListener getSessionListener() {
539             return communicator;
540         }
541     }
542
543 }