Bug 4940 - correctly implement default-request-timeout-millis
[netconf.git] / opendaylight / 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.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import io.netty.util.concurrent.EventExecutor;
18 import java.io.File;
19 import java.math.BigDecimal;
20 import java.net.InetSocketAddress;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
27 import org.opendaylight.controller.config.threadpool.ThreadPool;
28 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
29 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
30 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
31 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
32 import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
33 import org.opendaylight.controller.sal.core.api.Broker;
34 import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
35 import org.opendaylight.controller.sal.core.api.Provider;
36 import org.opendaylight.netconf.client.NetconfClientDispatcher;
37 import org.opendaylight.netconf.client.NetconfClientSessionListener;
38 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
39 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
40 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
41 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
42 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
43 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
44 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
45 import org.opendaylight.netconf.sal.connect.netconf.NetconfStateSchemas;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
47 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.UserPreferences;
50 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
51 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
52 import org.opendaylight.netconf.topology.pipeline.TopologyMountPointFacade.ConnectionStatusListenerRegistration;
53 import org.opendaylight.protocol.framework.ReconnectStrategy;
54 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
55 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
56 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
57 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
60 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
61 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
62 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
63 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
64 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
65 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
66 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
67 import org.opendaylight.yangtools.yang.binding.Identifier;
68 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
69 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
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.YangTextSchemaSource;
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 yet in mdsal
266         // TODO remove this when mdsal starts supporting default values
267         final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null ? DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
268         final Long keepaliveDelay = node.getKeepaliveDelay() == null ? DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
269         final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null ? DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
270
271         IpAddress ipAddress = node.getHost().getIpAddress();
272         InetSocketAddress address = new InetSocketAddress(ipAddress.getIpv4Address() != null ?
273                 ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue(),
274                 node.getPort().getValue());
275         RemoteDeviceId remoteDeviceId = new RemoteDeviceId(nodeId.getValue(), address);
276
277         RemoteDeviceHandler<NetconfSessionPreferences> salFacade =
278                 createSalFacade(remoteDeviceId, domBroker, bindingAwareBroker);
279
280         if (keepaliveDelay > 0) {
281             LOG.warn("Adding keepalive facade, for device {}", nodeId);
282             salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade, keepaliveExecutor.getExecutor(), keepaliveDelay, defaultRequestTimeoutMillis);
283         }
284
285         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = setupSchemaCacheDTO(nodeId, node);
286
287         final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, remoteDeviceId, salFacade,
288                 processingExecutor.getExecutor(), reconnectOnChangedSchema);
289
290         final Optional<NetconfSessionPreferences> userCapabilities = getUserCapabilities(node);
291
292         return new NetconfConnectorDTO(
293                 userCapabilities.isPresent() ?
294                         new NetconfDeviceCommunicator(
295                                 remoteDeviceId, device, new UserPreferences(userCapabilities.get(), node.getYangModuleCapabilities().isOverride())):
296                         new NetconfDeviceCommunicator(remoteDeviceId, device)
297                 , salFacade);
298     }
299
300     protected NetconfDevice.SchemaResourcesDTO setupSchemaCacheDTO(final NodeId nodeId, final NetconfNode node) {
301         // Setup information related to the SchemaRegistry, SchemaResourceFactory, etc.
302         NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = null;
303         final String moduleSchemaCacheDirectory = node.getSchemaCacheDirectory();
304         // Only checks to ensure the String is not empty or null;  further checks related to directory accessibility and file permissions
305         // are handled during the FilesystemScehamSourceCache initialization.
306         if (!Strings.isNullOrEmpty(moduleSchemaCacheDirectory)) {
307             // If a custom schema cache directory is specified, create the backing DTO; otherwise, the SchemaRegistry and
308             // SchemaContextFactory remain the default values.
309             if (!moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
310                 // Multiple modules may be created at once;  synchronize to avoid issues with data consistency among threads.
311                 synchronized(schemaResourcesDTOs) {
312                     // Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables if they already exist
313                     schemaResourcesDTO = schemaResourcesDTOs.get(moduleSchemaCacheDirectory);
314                     if (schemaResourcesDTO == null) {
315                         schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory, nodeId.getValue());
316                         schemaResourcesDTO.getSchemaRegistry().registerSchemaSourceListener(
317                                 TextToASTTransformer.create((SchemaRepository) schemaResourcesDTO.getSchemaRegistry(), schemaResourcesDTO.getSchemaRegistry())
318                         );
319                         schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
320                     }
321                 }
322                 LOG.info("Netconf connector for device {} will use schema cache directory {} instead of {}",
323                         nodeId.getValue(), moduleSchemaCacheDirectory, DEFAULT_CACHE_DIRECTORY);
324             }
325         } else {
326             LOG.warn("schema-cache-directory for {} is null or empty;  using the default {}",
327                     nodeId.getValue(), QUALIFIED_DEFAULT_CACHE_DIRECTORY);
328         }
329
330         if (schemaResourcesDTO == null) {
331             schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaContextFactory,
332                     new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
333         }
334
335         return schemaResourcesDTO;
336     }
337
338     /**
339      * Creates the backing Schema classes for a particular directory.
340      *
341      * @param moduleSchemaCacheDirectory The string directory relative to "cache"
342      * @return A DTO containing the Schema classes for the Netconf mount.
343      */
344     private NetconfDevice.SchemaResourcesDTO createSchemaResourcesDTO(final String moduleSchemaCacheDirectory,
345             final String instanceName) {
346
347         final SharedSchemaRepository repository = new SharedSchemaRepository(moduleSchemaCacheDirectory);
348         final SchemaContextFactory schemaContextFactory
349                 = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
350         setSchemaRegistry(repository);
351         setSchemaContextFactory(schemaContextFactory);
352         final FilesystemSchemaSourceCache<YangTextSchemaSource> deviceCache =
353                 createDeviceFilesystemCache(moduleSchemaCacheDirectory);
354         repository.registerSchemaSourceListener(deviceCache);
355         return new NetconfDevice.SchemaResourcesDTO(repository, schemaContextFactory,
356                 new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
357     }
358
359     /**
360      * Creates a <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory.
361      *
362      * @param schemaCacheDirectory The custom cache directory relative to "cache"
363      * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
364      */
365     private FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(final String schemaCacheDirectory) {
366         final String relativeSchemaCacheDirectory = CACHE_DIRECTORY + File.separator + schemaCacheDirectory;
367         return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class, new File(relativeSchemaCacheDirectory));
368     }
369
370     public NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener, NetconfNode node) {
371
372         //setup default values since default value is not supported yet in mdsal
373         // TODO remove this when mdsal starts supporting default values
374         final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null ? DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
375         final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null ? DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
376         final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null ? DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
377         final BigDecimal sleepFactor = node.getSleepFactor() == null ? DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
378
379         final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
380
381         final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
382                 maxConnectionAttempts, betweenAttemptsTimeoutMillis, sleepFactor);
383         final ReconnectStrategy strategy = sf.createReconnectStrategy();
384
385         final AuthenticationHandler authHandler;
386         final Credentials credentials = node.getCredentials();
387         if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) {
388             authHandler = new LoginPassword(
389                     ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getUsername(),
390                     ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.credentials.LoginPassword) credentials).getPassword());
391         } else {
392             throw new IllegalStateException("Only login/password authentification is supported");
393         }
394
395         return NetconfReconnectingClientConfigurationBuilder.create()
396                 .withAddress(socketAddress)
397                 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
398                 .withReconnectStrategy(strategy)
399                 .withAuthHandler(authHandler)
400                 .withProtocol(node.isTcpOnly() ?
401                         NetconfClientConfiguration.NetconfClientProtocol.TCP :
402                         NetconfClientConfiguration.NetconfClientProtocol.SSH)
403                 .withConnectStrategyFactory(sf)
404                 .withSessionListener(listener)
405                 .build();
406     }
407
408     protected abstract RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id, final Broker domBroker, final BindingAwareBroker bindingBroker);
409
410     @Override
411     public abstract ConnectionStatusListenerRegistration registerConnectionStatusListener(NodeId node, RemoteDeviceHandler<NetconfSessionPreferences> listener);
412
413     @Override
414     public void onSessionInitiated(ProviderSession session) {
415         mountPointService = session.getService(DOMMountPointService.class);
416     }
417
418     @Override
419     public Collection<ProviderFunctionality> getProviderFunctionality() {
420         return Collections.emptySet();
421     }
422
423     //TODO this needs to be an util method, since netconf clustering uses this aswell
424     /**
425      * Determines the Netconf Node Node ID, given the node's instance
426      * identifier.
427      *
428      * @param pathArgument Node's path arument
429      * @return     NodeId for the node
430      */
431     protected NodeId getNodeId(final PathArgument pathArgument) {
432         if (pathArgument instanceof InstanceIdentifier.IdentifiableItem<?, ?>) {
433
434             final Identifier key = ((InstanceIdentifier.IdentifiableItem) pathArgument).getKey();
435             if(key instanceof NodeKey) {
436                 return ((NodeKey) key).getNodeId();
437             }
438         }
439         throw new IllegalStateException("Unable to create NodeId from: " + pathArgument);
440     }
441
442     protected static InstanceIdentifier<Topology> createTopologyId(final String topologyId) {
443         final InstanceIdentifier<NetworkTopology> networkTopology = InstanceIdentifier.create(NetworkTopology.class);
444         return networkTopology.child(Topology.class, new TopologyKey(new TopologyId(topologyId)));
445     }
446
447     private InetSocketAddress getSocketAddress(final Host host, int port) {
448         if(host.getDomainName() != null) {
449             return new InetSocketAddress(host.getDomainName().getValue(), port);
450         } else {
451             final IpAddress ipAddress = host.getIpAddress();
452             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
453             return new InetSocketAddress(ip, port);
454         }
455     }
456
457     private Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
458         if(node.getYangModuleCapabilities() == null) {
459             return Optional.absent();
460         }
461
462         final List<String> capabilities = node.getYangModuleCapabilities().getCapability();
463         if(capabilities == null || capabilities.isEmpty()) {
464             return Optional.absent();
465         }
466
467         final NetconfSessionPreferences parsedOverrideCapabilities = NetconfSessionPreferences.fromStrings(capabilities);
468         Preconditions.checkState(parsedOverrideCapabilities.getNonModuleCaps().isEmpty(), "Capabilities to override can " +
469                 "only contain module based capabilities, non-module capabilities will be retrieved from the device," +
470                 " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps());
471
472         return Optional.of(parsedOverrideCapabilities);
473     }
474
475     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
476         private final Long connectionAttempts;
477         private final EventExecutor executor;
478         private final double sleepFactor;
479         private final int minSleep;
480
481         TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
482             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
483                 connectionAttempts = maxConnectionAttempts;
484             } else {
485                 connectionAttempts = null;
486             }
487
488             this.sleepFactor = sleepFactor.doubleValue();
489             this.executor = executor;
490             this.minSleep = minSleep;
491         }
492
493         @Override
494         public ReconnectStrategy createReconnectStrategy() {
495             final Long maxSleep = null;
496             final Long deadline = null;
497
498             return new TimedReconnectStrategy(executor, minSleep,
499                     minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
500         }
501     }
502
503     protected static class NetconfConnectorDTO {
504
505         private final NetconfDeviceCommunicator communicator;
506         private final RemoteDeviceHandler<NetconfSessionPreferences> facade;
507
508         public NetconfConnectorDTO(final NetconfDeviceCommunicator communicator, final RemoteDeviceHandler<NetconfSessionPreferences> facade) {
509             this.communicator = communicator;
510             this.facade = facade;
511         }
512
513         public NetconfDeviceCommunicator getCommunicator() {
514             return communicator;
515         }
516
517         public RemoteDeviceHandler<NetconfSessionPreferences> getFacade() {
518             return facade;
519         }
520
521         public NetconfClientSessionListener getSessionListener() {
522             return communicator;
523         }
524     }
525
526 }