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