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