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