BUG 5634 : Implement concurrent message limit
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / controller / config / yang / md / sal / connector / netconf / NetconfConnectorModule.java
1 /*
2  * Copyright (c) 2014 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 package org.opendaylight.controller.config.yang.md.sal.connector.netconf;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkCondition;
12 import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkNotNull;
13
14 import com.google.common.base.Optional;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.Lists;
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.net.URL;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.concurrent.ExecutorService;
26 import java.util.concurrent.Executors;
27 import java.util.concurrent.ScheduledExecutorService;
28 import java.util.concurrent.ThreadFactory;
29 import org.opendaylight.controller.config.api.JmxAttributeValidationException;
30 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
31 import org.opendaylight.controller.config.threadpool.ThreadPool;
32 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
33 import org.opendaylight.controller.sal.core.api.Broker;
34 import org.opendaylight.netconf.client.NetconfClientDispatcher;
35 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
36 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
37 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
38 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
39 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
40 import org.opendaylight.netconf.sal.connect.netconf.LibraryModulesSchemas;
41 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
42 import org.opendaylight.netconf.sal.connect.netconf.NetconfDeviceBuilder;
43 import org.opendaylight.netconf.sal.connect.netconf.NetconfStateSchemas;
44 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
45 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.UserPreferences;
47 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
48 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceSalFacade;
49 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
50 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
51 import org.opendaylight.protocol.framework.ReconnectStrategy;
52 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
53 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
54 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
58 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
59 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
60 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
61 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
62 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
63 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
64 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
65 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
66 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
67 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
68 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
69 import org.osgi.framework.BundleContext;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72
73 /**
74  *
75  */
76 public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
77 {
78     private static final Logger LOG = LoggerFactory.getLogger(NetconfConnectorModule.class);
79
80     /**
81      * Filesystem based caches are stored relative to the cache directory.
82      */
83     private static final String CACHE_DIRECTORY = "cache";
84
85     /**
86      * The default cache directory relative to <code>CACHE_DIRECTORY</code>
87      */
88     private static final String DEFAULT_CACHE_DIRECTORY = "schema";
89
90     /**
91      * The qualified schema cache directory <code>cache/schema</code>
92      */
93     private static final String QUALIFIED_DEFAULT_CACHE_DIRECTORY = CACHE_DIRECTORY + File.separator+ DEFAULT_CACHE_DIRECTORY;
94
95     /**
96      * The name for the default schema repository
97      */
98     private static final String DEFAULT_SCHEMA_REPOSITORY_NAME = "sal-netconf-connector";
99
100     /**
101      * The default schema repository in the case that one is not specified.
102      */
103     private static final SharedSchemaRepository DEFAULT_SCHEMA_REPOSITORY =
104             new SharedSchemaRepository(DEFAULT_SCHEMA_REPOSITORY_NAME);
105
106     /**
107      * The default <code>FilesystemSchemaSourceCache</code>, which stores cached files in <code>cache/schema</code>.
108      */
109     private static final FilesystemSchemaSourceCache<YangTextSchemaSource> DEFAULT_CACHE =
110             new FilesystemSchemaSourceCache<>(DEFAULT_SCHEMA_REPOSITORY, YangTextSchemaSource.class,
111                     new File(QUALIFIED_DEFAULT_CACHE_DIRECTORY));
112
113     /**
114      * The default factory for creating <code>SchemaContext</code> instances.
115      */
116     private static final SchemaContextFactory DEFAULT_SCHEMA_CONTEXT_FACTORY =
117             DEFAULT_SCHEMA_REPOSITORY.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
118
119     private static final int LOCAL_IO_FALLBACK_COST = PotentialSchemaSource.Costs.LOCAL_IO.getValue() + 1;
120
121     /**
122      * Keeps track of initialized Schema resources.  A Map is maintained in which the key represents the name
123      * of the schema cache directory, and the value is a corresponding <code>SchemaResourcesDTO</code>.  The
124      * <code>SchemaResourcesDTO</code> is essentially a container that allows for the extraction of the
125      * <code>SchemaRegistry</code> and <code>SchemaContextFactory</code> which should be used for a particular
126      * Netconf mount.  Access to <code>schemaResourcesDTOs</code> should be surrounded by appropriate
127      * synchronization locks.
128      */
129     private static volatile Map<String, NetconfDevice.SchemaResourcesDTO> schemaResourcesDTOs = new HashMap<>();
130
131     // Initializes default constant instances for the case when the default schema repository
132     // directory cache/schema is used.
133     static {
134         schemaResourcesDTOs.put(DEFAULT_CACHE_DIRECTORY,
135                 new NetconfDevice.SchemaResourcesDTO(DEFAULT_SCHEMA_REPOSITORY,
136                         DEFAULT_SCHEMA_CONTEXT_FACTORY,
137                         new NetconfStateSchemas.NetconfStateSchemasResolverImpl()));
138         DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(DEFAULT_CACHE);
139         DEFAULT_SCHEMA_REPOSITORY.registerSchemaSourceListener(
140                 TextToASTTransformer.create(DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY));
141     }
142
143     private BundleContext bundleContext;
144     private Optional<NetconfSessionPreferences> userCapabilities;
145     private SchemaSourceRegistry schemaRegistry = DEFAULT_SCHEMA_REPOSITORY;
146     private SchemaContextFactory schemaContextFactory = DEFAULT_SCHEMA_CONTEXT_FACTORY;
147
148     private Broker domRegistry;
149     private NetconfClientDispatcher clientDispatcher;
150     private BindingAwareBroker bindingRegistry;
151     private ThreadPool processingExecutor;
152     private ScheduledThreadPool keepaliveExecutor;
153     private EventExecutor eventExecutor;
154
155     /**
156      * The name associated with the Netconf mount point.  This value is passed from <code>NetconfConnectorModuleFactory</code>.
157      */
158     private String instanceName;
159
160     public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
161         super(identifier, dependencyResolver);
162     }
163
164     public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final NetconfConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) {
165         super(identifier, dependencyResolver, oldModule, oldInstance);
166     }
167
168     @Override
169     protected void customValidation() {
170         checkNotNull(getAddress(), addressJmxAttribute);
171         checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
172         checkNotNull(getPort(), portJmxAttribute);
173
174         checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
175         checkCondition(getConnectionTimeoutMillis() > 0, "must be > 0", connectionTimeoutMillisJmxAttribute);
176
177         checkNotNull(getDefaultRequestTimeoutMillis(), defaultRequestTimeoutMillisJmxAttribute);
178         checkCondition(getDefaultRequestTimeoutMillis() > 0, "must be > 0", defaultRequestTimeoutMillisJmxAttribute);
179
180         checkNotNull(getBetweenAttemptsTimeoutMillis(), betweenAttemptsTimeoutMillisJmxAttribute);
181         checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
182
183         // Check username + password in case of ssh
184         if(getTcpOnly() == false) {
185             checkNotNull(getUsername(), usernameJmxAttribute);
186             checkNotNull(getPassword(), passwordJmxAttribute);
187         }
188
189         userCapabilities = getUserCapabilities();
190     }
191
192     private boolean isHostAddressPresent(final Host address) {
193         return address.getDomainName() != null ||
194                address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
195     }
196
197     @Deprecated
198     private static ScheduledExecutorService DEFAULT_KEEPALIVE_EXECUTOR;
199
200     @Override
201     public java.lang.AutoCloseable createInstance() {
202         initDependencies();
203         final RemoteDeviceId id = new RemoteDeviceId(getIdentifier(), getSocketAddress());
204
205         final ExecutorService globalProcessingExecutor = processingExecutor.getExecutor();
206
207         RemoteDeviceHandler<NetconfSessionPreferences> salFacade
208                 = new NetconfDeviceSalFacade(id, domRegistry, bindingRegistry);
209
210         final Long keepaliveDelay = getKeepaliveDelay();
211         if (shouldSendKeepalive()) {
212             // Keepalive executor is optional for now and a default instance is supported
213             final ScheduledExecutorService executor = keepaliveExecutor == null ? DEFAULT_KEEPALIVE_EXECUTOR : keepaliveExecutor.getExecutor();
214
215             salFacade = new KeepaliveSalFacade(id, salFacade, executor, keepaliveDelay, getDefaultRequestTimeoutMillis());
216         }
217
218         // Setup information related to the SchemaRegistry, SchemaResourceFactory, etc.
219         NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = null;
220         final String moduleSchemaCacheDirectory = getSchemaCacheDirectory();
221         // Only checks to ensure the String is not empty or null;  further checks related to directory accessibility and file permissions
222         // are handled during the FilesystemSchemaSourceCache initialization.
223         if (!Strings.isNullOrEmpty(moduleSchemaCacheDirectory)) {
224             // If a custom schema cache directory is specified, create the backing DTO; otherwise, the SchemaRegistry and
225             // SchemaContextFactory remain the default values.
226             if (!moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
227                 // Multiple modules may be created at once;  synchronize to avoid issues with data consistency among threads.
228                 synchronized(schemaResourcesDTOs) {
229                     // Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables if they already exist
230                     final NetconfDevice.SchemaResourcesDTO dto =
231                             schemaResourcesDTOs.get(moduleSchemaCacheDirectory);
232                     if (dto == null) {
233                         schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory);
234                         schemaRegistry.registerSchemaSourceListener(
235                                 TextToASTTransformer.create((SchemaRepository) schemaRegistry, schemaRegistry));
236                         schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
237                     } else {
238                         setSchemaContextFactory(dto.getSchemaContextFactory());
239                         setSchemaRegistry(dto.getSchemaRegistry());
240                         schemaResourcesDTO = dto;
241                     }
242                     if (userCapabilities.isPresent()) {
243                         for (QName qname : userCapabilities.get().getModuleBasedCaps()) {
244                             final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier
245                                     .create(qname.getLocalName(), qname.getFormattedRevision());
246                             dto.getSchemaRegistry().registerSchemaSource(DEFAULT_CACHE, PotentialSchemaSource
247                                     .create(sourceIdentifier, YangTextSchemaSource.class, LOCAL_IO_FALLBACK_COST));
248                         }
249                     }
250                 }
251                 LOG.info("Netconf connector for device {} will use schema cache directory {} instead of {}",
252                         instanceName, moduleSchemaCacheDirectory, DEFAULT_CACHE_DIRECTORY);
253             }
254         } else {
255             LOG.warn("schema-cache-directory for {} is null or empty;  using the default {}",
256                     instanceName, QUALIFIED_DEFAULT_CACHE_DIRECTORY);
257         }
258
259         // pre register yang library sources as fallback schemas to schema registry
260         List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
261         if (getYangLibrary() != null) {
262             final String yangLibURL = getYangLibrary().getYangLibraryUrl().getValue();
263             final String yangLibUsername = getYangLibrary().getUsername();
264             final String yangLigPassword = getYangLibrary().getPassword();
265
266             LibraryModulesSchemas libraryModulesSchemas;
267             if(yangLibURL != null) {
268                 if(yangLibUsername != null && yangLigPassword != null) {
269                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
270                 } else {
271                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
272                 }
273
274                 for (Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry : libraryModulesSchemas.getAvailableModels().entrySet()) {
275                     registeredYangLibSources.
276                             add(schemaRegistry.registerSchemaSource(
277                                     new YangLibrarySchemaYangSourceProvider(id, libraryModulesSchemas.getAvailableModels()),
278                                     PotentialSchemaSource
279                                             .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
280                                                     PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
281                 }
282             }
283         }
284
285         if (schemaResourcesDTO == null) {
286             schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaContextFactory,
287                     new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
288         }
289
290         final NetconfDevice device = new NetconfDeviceBuilder()
291                 .setReconnectOnSchemasChange(getReconnectOnChangedSchema())
292                 .setSchemaResourcesDTO(schemaResourcesDTO)
293                 .setGlobalProcessingExecutor(globalProcessingExecutor)
294                 .setId(id)
295                 .setSalFacade(salFacade)
296                 .build();
297
298         if (getConcurrentRpcLimit() < 1) {
299             LOG.info("Concurrent rpc limit is smaller than 1, no limit will be enforced for device {}", id);
300         }
301
302         final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
303                 new NetconfDeviceCommunicator(id, device,
304                         new UserPreferences(userCapabilities.get(), getYangModuleCapabilities().getOverride()), getConcurrentRpcLimit()):
305                 new NetconfDeviceCommunicator(id, device, getConcurrentRpcLimit());
306
307         if (shouldSendKeepalive()) {
308             ((KeepaliveSalFacade) salFacade).setListener(listener);
309         }
310
311         final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
312         listener.initializeRemoteConnection(clientDispatcher, clientConfig);
313
314         return new SalConnectorCloseable(listener, salFacade, registeredYangLibSources);
315     }
316
317     /**
318      * Creates the backing Schema classes for a particular directory.
319      *
320      * @param moduleSchemaCacheDirectory The string directory relative to "cache"
321      * @return A DTO containing the Schema classes for the Netconf mount.
322      */
323     private NetconfDevice.SchemaResourcesDTO createSchemaResourcesDTO(final String moduleSchemaCacheDirectory) {
324         final SharedSchemaRepository repository = new SharedSchemaRepository(instanceName);
325         final SchemaContextFactory schemaContextFactory
326                 = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
327         setSchemaRegistry(repository);
328         setSchemaContextFactory(schemaContextFactory);
329         final FilesystemSchemaSourceCache<YangTextSchemaSource> deviceCache =
330                 createDeviceFilesystemCache(moduleSchemaCacheDirectory);
331         repository.registerSchemaSourceListener(deviceCache);
332         return new NetconfDevice.SchemaResourcesDTO(repository, schemaContextFactory,
333                 new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
334     }
335
336     /**
337      * Creates a <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory.
338      *
339      * @param schemaCacheDirectory The custom cache directory relative to "cache"
340      * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
341      */
342     private FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(final String schemaCacheDirectory) {
343         final String relativeSchemaCacheDirectory = CACHE_DIRECTORY + File.separator + schemaCacheDirectory;
344         return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class, new File(relativeSchemaCacheDirectory));
345     }
346
347     private void initDependencies() {
348         domRegistry = getDomRegistryDependency();
349         clientDispatcher = getClientDispatcherDependency();
350         bindingRegistry = getBindingRegistryDependency();
351         processingExecutor = getProcessingExecutorDependency();
352         eventExecutor = getEventExecutorDependency();
353
354         if(getKeepaliveExecutor() == null) {
355             LOG.warn("Keepalive executor missing. Using default instance for now, the configuration needs to be updated");
356
357             // Instantiate the default executor, now we know its necessary
358             if(DEFAULT_KEEPALIVE_EXECUTOR == null) {
359                 DEFAULT_KEEPALIVE_EXECUTOR = Executors.newScheduledThreadPool(2, new ThreadFactory() {
360                     @Override
361                     public Thread newThread(final Runnable r) {
362                         final Thread thread = new Thread(r);
363                         thread.setName("netconf-southound-keepalives-" + thread.getId());
364                         thread.setDaemon(true);
365                         return thread;
366                     }
367                 });
368             }
369         } else {
370             keepaliveExecutor = getKeepaliveExecutorDependency();
371         }
372     }
373
374     private boolean shouldSendKeepalive() {
375         return getKeepaliveDelay() > 0;
376     }
377
378     private Optional<NetconfSessionPreferences> getUserCapabilities() {
379         if(getYangModuleCapabilities() == null) {
380             return Optional.absent();
381         }
382
383         final List<String> capabilities = getYangModuleCapabilities().getCapability();
384         if(capabilities == null || capabilities.isEmpty()) {
385             return Optional.absent();
386         }
387
388         final NetconfSessionPreferences parsedOverrideCapabilities = NetconfSessionPreferences.fromStrings(capabilities);
389         JmxAttributeValidationException.checkCondition(
390                 parsedOverrideCapabilities.getNonModuleCaps().isEmpty(),
391                 "Capabilities to override can only contain module based capabilities, non-module capabilities will be retrieved from the device," +
392                         " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps(),
393                 yangModuleCapabilitiesJmxAttribute);
394
395         return Optional.of(parsedOverrideCapabilities);
396     }
397
398     public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDeviceCommunicator listener) {
399         final InetSocketAddress socketAddress = getSocketAddress();
400         final long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
401
402         final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
403                 getMaxConnectionAttempts(), getBetweenAttemptsTimeoutMillis(), getSleepFactor());
404         final ReconnectStrategy strategy = sf.createReconnectStrategy();
405
406         return NetconfReconnectingClientConfigurationBuilder.create()
407         .withAddress(socketAddress)
408         .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
409         .withReconnectStrategy(strategy)
410         .withAuthHandler(new LoginPassword(getUsername(), getPassword()))
411         .withProtocol(getTcpOnly() ?
412                 NetconfClientConfiguration.NetconfClientProtocol.TCP :
413                 NetconfClientConfiguration.NetconfClientProtocol.SSH)
414         .withConnectStrategyFactory(sf)
415         .withSessionListener(listener)
416         .build();
417     }
418
419     private static final class SalConnectorCloseable implements AutoCloseable {
420         private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
421         private final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources;
422         private final NetconfDeviceCommunicator listener;
423
424         public SalConnectorCloseable(final NetconfDeviceCommunicator listener,
425                                      final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
426                                      final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources) {
427             this.listener = listener;
428             this.salFacade = salFacade;
429             this.registeredYangLibSources = registeredYangLibSources;
430         }
431
432         @Override
433         public void close() {
434             for (SchemaSourceRegistration<YangTextSchemaSource> registeredYangLibSource : registeredYangLibSources) {
435                 registeredYangLibSource.close();
436             }
437             listener.close();
438             salFacade.close();
439         }
440     }
441
442     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
443         private final Long connectionAttempts;
444         private final EventExecutor executor;
445         private final double sleepFactor;
446         private final int minSleep;
447
448         TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
449             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
450                 connectionAttempts = maxConnectionAttempts;
451             } else {
452                 LOG.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
453                 connectionAttempts = null;
454             }
455
456             this.sleepFactor = sleepFactor.doubleValue();
457             this.executor = executor;
458             this.minSleep = minSleep;
459         }
460
461         @Override
462         public ReconnectStrategy createReconnectStrategy() {
463             final Long maxSleep = null;
464             final Long deadline = null;
465
466             return new TimedReconnectStrategy(executor, minSleep,
467                     minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
468         }
469     }
470
471     private InetSocketAddress getSocketAddress() {
472         if(getAddress().getDomainName() != null) {
473             return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
474         } else {
475             final IpAddress ipAddress = getAddress().getIpAddress();
476             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
477             return new InetSocketAddress(ip, getPort().getValue());
478         }
479     }
480
481     public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
482         this.schemaRegistry = schemaRegistry;
483     }
484
485     public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
486         this.schemaContextFactory = schemaContextFactory;
487     }
488
489     public void setInstanceName(final String instanceName) {
490         this.instanceName = instanceName;
491     }
492 }