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