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