Bug 6198 - Use sal-netconf-connector to connet device costs too much time
[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.NetconfStateSchemasResolverImpl;
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.rev130715.Host;
55 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.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, DEFAULT_SCHEMA_REPOSITORY,
136                         DEFAULT_SCHEMA_CONTEXT_FACTORY,
137                         new 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 SchemaRepository schemaRepository = DEFAULT_SCHEMA_REPOSITORY;
147     private SchemaContextFactory schemaContextFactory = DEFAULT_SCHEMA_CONTEXT_FACTORY;
148
149     private Broker domRegistry;
150     private NetconfClientDispatcher clientDispatcher;
151     private BindingAwareBroker bindingRegistry;
152     private ThreadPool processingExecutor;
153     private ScheduledThreadPool keepaliveExecutor;
154     private EventExecutor eventExecutor;
155
156     /**
157      * The name associated with the Netconf mount point.  This value is passed from <code>NetconfConnectorModuleFactory</code>.
158      */
159     private String instanceName;
160
161     public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
162         super(identifier, dependencyResolver);
163     }
164
165     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) {
166         super(identifier, dependencyResolver, oldModule, oldInstance);
167     }
168
169     @Override
170     protected void customValidation() {
171         checkNotNull(getAddress(), addressJmxAttribute);
172         checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
173         checkNotNull(getPort(), portJmxAttribute);
174
175         checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
176         checkCondition(getConnectionTimeoutMillis() > 0, "must be > 0", connectionTimeoutMillisJmxAttribute);
177
178         checkNotNull(getDefaultRequestTimeoutMillis(), defaultRequestTimeoutMillisJmxAttribute);
179         checkCondition(getDefaultRequestTimeoutMillis() > 0, "must be > 0", defaultRequestTimeoutMillisJmxAttribute);
180
181         checkNotNull(getBetweenAttemptsTimeoutMillis(), betweenAttemptsTimeoutMillisJmxAttribute);
182         checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
183
184         // Check username + password in case of ssh
185         if(getTcpOnly() == false) {
186             checkNotNull(getUsername(), usernameJmxAttribute);
187             checkNotNull(getPassword(), passwordJmxAttribute);
188         }
189
190         userCapabilities = getUserCapabilities();
191     }
192
193     private boolean isHostAddressPresent(final Host address) {
194         return address.getDomainName() != null ||
195                address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
196     }
197
198     @Deprecated
199     private static ScheduledExecutorService DEFAULT_KEEPALIVE_EXECUTOR;
200
201     @Override
202     public java.lang.AutoCloseable createInstance() {
203         initDependencies();
204         final RemoteDeviceId id = new RemoteDeviceId(getIdentifier(), getSocketAddress());
205
206         final ExecutorService globalProcessingExecutor = processingExecutor.getExecutor();
207
208         RemoteDeviceHandler<NetconfSessionPreferences> salFacade
209                 = new NetconfDeviceSalFacade(id, domRegistry, bindingRegistry);
210
211         final Long keepaliveDelay = getKeepaliveDelay();
212         if (shouldSendKeepalive()) {
213             // Keepalive executor is optional for now and a default instance is supported
214             final ScheduledExecutorService executor = keepaliveExecutor == null ? DEFAULT_KEEPALIVE_EXECUTOR : keepaliveExecutor.getExecutor();
215
216             salFacade = new KeepaliveSalFacade(id, salFacade, executor, keepaliveDelay, getDefaultRequestTimeoutMillis());
217         }
218
219         // Setup information related to the SchemaRegistry, SchemaResourceFactory, etc.
220         NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = null;
221         final String moduleSchemaCacheDirectory = getSchemaCacheDirectory();
222         // Only checks to ensure the String is not empty or null;  further checks related to directory accessibility and file permissions
223         // are handled during the FilesystemSchemaSourceCache initialization.
224         if (!Strings.isNullOrEmpty(moduleSchemaCacheDirectory)) {
225             // If a custom schema cache directory is specified, create the backing DTO; otherwise, the SchemaRegistry and
226             // SchemaContextFactory remain the default values.
227             if (!moduleSchemaCacheDirectory.equals(DEFAULT_CACHE_DIRECTORY)) {
228                 // Multiple modules may be created at once;  synchronize to avoid issues with data consistency among threads.
229                 synchronized(schemaResourcesDTOs) {
230                     // Look for the cached DTO to reuse SchemaRegistry and SchemaContextFactory variables if they already exist
231                     final NetconfDevice.SchemaResourcesDTO dto =
232                             schemaResourcesDTOs.get(moduleSchemaCacheDirectory);
233                     if (dto == null) {
234                         schemaResourcesDTO = createSchemaResourcesDTO(moduleSchemaCacheDirectory);
235                         schemaRegistry.registerSchemaSourceListener(
236                                 TextToASTTransformer.create((SchemaRepository) schemaRegistry, schemaRegistry));
237                         schemaResourcesDTOs.put(moduleSchemaCacheDirectory, schemaResourcesDTO);
238                     } else {
239                         setSchemaContextFactory(dto.getSchemaContextFactory());
240                         setSchemaRegistry(dto.getSchemaRegistry());
241                         schemaResourcesDTO = dto;
242                     }
243                     if (userCapabilities.isPresent()) {
244                         for (QName qname : userCapabilities.get().getModuleBasedCaps()) {
245                             final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier
246                                     .create(qname.getLocalName(), qname.getFormattedRevision());
247                             dto.getSchemaRegistry().registerSchemaSource(DEFAULT_CACHE, PotentialSchemaSource
248                                     .create(sourceIdentifier, YangTextSchemaSource.class, LOCAL_IO_FALLBACK_COST));
249                         }
250                     }
251                 }
252                 LOG.info("Netconf connector for device {} will use schema cache directory {} instead of {}",
253                         instanceName, moduleSchemaCacheDirectory, DEFAULT_CACHE_DIRECTORY);
254             }
255         } else {
256             LOG.warn("schema-cache-directory for {} is null or empty;  using the default {}",
257                     instanceName, QUALIFIED_DEFAULT_CACHE_DIRECTORY);
258         }
259
260         // pre register yang library sources as fallback schemas to schema registry
261         List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
262         if (getYangLibrary() != null) {
263             final String yangLibURL = getYangLibrary().getYangLibraryUrl().getValue();
264             final String yangLibUsername = getYangLibrary().getUsername();
265             final String yangLigPassword = getYangLibrary().getPassword();
266
267             LibraryModulesSchemas libraryModulesSchemas;
268             if(yangLibURL != null) {
269                 if(yangLibUsername != null && yangLigPassword != null) {
270                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
271                 } else {
272                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
273                 }
274
275                 for (Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry : libraryModulesSchemas.getAvailableModels().entrySet()) {
276                     registeredYangLibSources.
277                             add(schemaRegistry.registerSchemaSource(
278                                     new YangLibrarySchemaYangSourceProvider(id, libraryModulesSchemas.getAvailableModels()),
279                                     PotentialSchemaSource
280                                             .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
281                                                     PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
282                 }
283             }
284         }
285
286         if (schemaResourcesDTO == null) {
287             schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaRepository, schemaContextFactory,
288                     new NetconfStateSchemasResolverImpl());
289         }
290
291         final NetconfDevice device = new NetconfDeviceBuilder()
292                 .setReconnectOnSchemasChange(getReconnectOnChangedSchema())
293                 .setSchemaResourcesDTO(schemaResourcesDTO)
294                 .setGlobalProcessingExecutor(globalProcessingExecutor)
295                 .setId(id)
296                 .setSalFacade(salFacade)
297                 .build();
298
299         if (getConcurrentRpcLimit() < 1) {
300             LOG.info("Concurrent rpc limit is smaller than 1, no limit will be enforced for device {}", id);
301         }
302
303         final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
304                 new NetconfDeviceCommunicator(id, device,
305                         new UserPreferences(userCapabilities.get(), getYangModuleCapabilities().getOverride()), getConcurrentRpcLimit()):
306                 new NetconfDeviceCommunicator(id, device, getConcurrentRpcLimit());
307
308         if (shouldSendKeepalive()) {
309             ((KeepaliveSalFacade) salFacade).setListener(listener);
310         }
311
312         final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
313         listener.initializeRemoteConnection(clientDispatcher, clientConfig);
314
315         return new SalConnectorCloseable(listener, salFacade, registeredYangLibSources);
316     }
317
318     /**
319      * Creates the backing Schema classes for a particular directory.
320      *
321      * @param moduleSchemaCacheDirectory The string directory relative to "cache"
322      * @return A DTO containing the Schema classes for the Netconf mount.
323      */
324     private NetconfDevice.SchemaResourcesDTO createSchemaResourcesDTO(final String moduleSchemaCacheDirectory) {
325         final SharedSchemaRepository repository = new SharedSchemaRepository(instanceName);
326         final SchemaContextFactory schemaContextFactory
327                 = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
328         setSchemaRegistry(repository);
329         setSchemaContextFactory(schemaContextFactory);
330         final FilesystemSchemaSourceCache<YangTextSchemaSource> deviceCache =
331                 createDeviceFilesystemCache(moduleSchemaCacheDirectory);
332         repository.registerSchemaSourceListener(deviceCache);
333         return new NetconfDevice.SchemaResourcesDTO(repository, repository, schemaContextFactory,
334                 new NetconfStateSchemasResolverImpl());
335     }
336
337     /**
338      * Creates a <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory.
339      *
340      * @param schemaCacheDirectory The custom cache directory relative to "cache"
341      * @return A <code>FilesystemSchemaSourceCache</code> for the custom schema cache directory
342      */
343     private FilesystemSchemaSourceCache<YangTextSchemaSource> createDeviceFilesystemCache(final String schemaCacheDirectory) {
344         final String relativeSchemaCacheDirectory = CACHE_DIRECTORY + File.separator + schemaCacheDirectory;
345         return new FilesystemSchemaSourceCache<>(schemaRegistry, YangTextSchemaSource.class, new File(relativeSchemaCacheDirectory));
346     }
347
348     private void initDependencies() {
349         domRegistry = getDomRegistryDependency();
350         clientDispatcher = getClientDispatcherDependency();
351         bindingRegistry = getBindingRegistryDependency();
352         processingExecutor = getProcessingExecutorDependency();
353         eventExecutor = getEventExecutorDependency();
354
355         if(getKeepaliveExecutor() == null) {
356             LOG.warn("Keepalive executor missing. Using default instance for now, the configuration needs to be updated");
357
358             // Instantiate the default executor, now we know its necessary
359             if(DEFAULT_KEEPALIVE_EXECUTOR == null) {
360                 DEFAULT_KEEPALIVE_EXECUTOR = Executors.newScheduledThreadPool(2, new ThreadFactory() {
361                     @Override
362                     public Thread newThread(final Runnable r) {
363                         final Thread thread = new Thread(r);
364                         thread.setName("netconf-southound-keepalives-" + thread.getId());
365                         thread.setDaemon(true);
366                         return thread;
367                     }
368                 });
369             }
370         } else {
371             keepaliveExecutor = getKeepaliveExecutorDependency();
372         }
373     }
374
375     private boolean shouldSendKeepalive() {
376         return getKeepaliveDelay() > 0;
377     }
378
379     private Optional<NetconfSessionPreferences> getUserCapabilities() {
380         if(getYangModuleCapabilities() == null) {
381             return Optional.absent();
382         }
383
384         final List<String> capabilities = getYangModuleCapabilities().getCapability();
385         if(capabilities == null || capabilities.isEmpty()) {
386             return Optional.absent();
387         }
388
389         final NetconfSessionPreferences parsedOverrideCapabilities = NetconfSessionPreferences.fromStrings(capabilities);
390         JmxAttributeValidationException.checkCondition(
391                 parsedOverrideCapabilities.getNonModuleCaps().isEmpty(),
392                 "Capabilities to override can only contain module based capabilities, non-module capabilities will be retrieved from the device," +
393                         " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps(),
394                 yangModuleCapabilitiesJmxAttribute);
395
396         return Optional.of(parsedOverrideCapabilities);
397     }
398
399     public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDeviceCommunicator listener) {
400         final InetSocketAddress socketAddress = getSocketAddress();
401         final long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
402
403         final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(eventExecutor,
404                 getMaxConnectionAttempts(), getBetweenAttemptsTimeoutMillis(), getSleepFactor());
405         final ReconnectStrategy strategy = sf.createReconnectStrategy();
406
407         return NetconfReconnectingClientConfigurationBuilder.create()
408         .withAddress(socketAddress)
409         .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
410         .withReconnectStrategy(strategy)
411         .withAuthHandler(new LoginPassword(getUsername(), getPassword()))
412         .withProtocol(getTcpOnly() ?
413                 NetconfClientConfiguration.NetconfClientProtocol.TCP :
414                 NetconfClientConfiguration.NetconfClientProtocol.SSH)
415         .withConnectStrategyFactory(sf)
416         .withSessionListener(listener)
417         .build();
418     }
419
420     private static final class SalConnectorCloseable implements AutoCloseable {
421         private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
422         private final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources;
423         private final NetconfDeviceCommunicator listener;
424
425         public SalConnectorCloseable(final NetconfDeviceCommunicator listener,
426                                      final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
427                                      final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources) {
428             this.listener = listener;
429             this.salFacade = salFacade;
430             this.registeredYangLibSources = registeredYangLibSources;
431         }
432
433         @Override
434         public void close() {
435             for (SchemaSourceRegistration<YangTextSchemaSource> registeredYangLibSource : registeredYangLibSources) {
436                 registeredYangLibSource.close();
437             }
438             listener.close();
439             salFacade.close();
440         }
441     }
442
443     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
444         private final Long connectionAttempts;
445         private final EventExecutor executor;
446         private final double sleepFactor;
447         private final int minSleep;
448
449         TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
450             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
451                 connectionAttempts = maxConnectionAttempts;
452             } else {
453                 LOG.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
454                 connectionAttempts = null;
455             }
456
457             this.sleepFactor = sleepFactor.doubleValue();
458             this.executor = executor;
459             this.minSleep = minSleep;
460         }
461
462         @Override
463         public ReconnectStrategy createReconnectStrategy() {
464             final Long maxSleep = null;
465             final Long deadline = null;
466
467             return new TimedReconnectStrategy(executor, minSleep,
468                     minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
469         }
470     }
471
472     private InetSocketAddress getSocketAddress() {
473         if(getAddress().getDomainName() != null) {
474             return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
475         } else {
476             final IpAddress ipAddress = getAddress().getIpAddress();
477             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
478             return new InetSocketAddress(ip, getPort().getValue());
479         }
480     }
481
482     public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
483         this.schemaRegistry = schemaRegistry;
484     }
485
486     public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
487         this.schemaContextFactory = schemaContextFactory;
488     }
489
490     public void setInstanceName(final String instanceName) {
491         this.instanceName = instanceName;
492     }
493 }