BUG-372 Add reconnecting to netconf-connector for unexpected session drop
[controller.git] / opendaylight / md-sal / 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 org.opendaylight.controller.config.api.JmxAttributeValidationException.checkCondition;
11 import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkNotNull;
12
13 import com.google.common.net.InetAddresses;
14 import io.netty.util.HashedWheelTimer;
15 import io.netty.util.concurrent.GlobalEventExecutor;
16 import java.io.File;
17 import java.io.InputStream;
18 import java.net.InetAddress;
19 import java.net.InetSocketAddress;
20 import java.util.concurrent.ExecutorService;
21 import java.util.concurrent.Executors;
22 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
23 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
24 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
25 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
26 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
27 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
28 import org.opendaylight.controller.netconf.util.handler.ssh.authentication.LoginPassword;
29 import org.opendaylight.controller.sal.binding.api.data.DataProviderService;
30 import org.opendaylight.controller.sal.connect.netconf.NetconfDevice;
31 import org.opendaylight.controller.sal.connect.netconf.NetconfDeviceListener;
32 import org.opendaylight.protocol.framework.ReconnectStrategy;
33 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
34 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.inventory.rev140108.NetconfNode;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.opendaylight.yangtools.yang.model.util.repo.AbstractCachingSchemaSourceProvider;
40 import org.opendaylight.yangtools.yang.model.util.repo.FilesystemSchemaCachingProvider;
41 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
42 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProviders;
43 import org.osgi.framework.BundleContext;
44 import org.osgi.framework.ServiceReference;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  *
50  */
51 public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
52 {
53     private static final Logger logger = LoggerFactory.getLogger(NetconfConnectorModule.class);
54
55     private static ExecutorService GLOBAL_PROCESSING_EXECUTOR = null;
56     private static AbstractCachingSchemaSourceProvider<String, InputStream> GLOBAL_NETCONF_SOURCE_PROVIDER = null;
57     private BundleContext bundleContext;
58
59     public NetconfConnectorModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
60         super(identifier, dependencyResolver);
61     }
62
63     public NetconfConnectorModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, NetconfConnectorModule oldModule, java.lang.AutoCloseable oldInstance) {
64         super(identifier, dependencyResolver, oldModule, oldInstance);
65     }
66
67     @Override
68     protected void customValidation() {
69         checkNotNull(getAddress(), addressJmxAttribute);
70         //checkState(getAddress().getIpv4Address() != null || getAddress().getIpv6Address() != null,"Address must be set.");
71         checkNotNull(getPort(), portJmxAttribute);
72         checkNotNull(getDomRegistry(), portJmxAttribute);
73         checkNotNull(getDomRegistry(), domRegistryJmxAttribute);
74
75         checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
76         checkCondition(getConnectionTimeoutMillis() > 0, "must be > 0", connectionTimeoutMillisJmxAttribute);
77
78         checkNotNull(getBetweenAttemptsTimeoutMillis(), betweenAttemptsTimeoutMillisJmxAttribute);
79         checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
80
81         // FIXME BUG-944 remove backwards compatibility
82         if(getClientDispatcher() == null) {
83             checkCondition(getBossThreadGroup() != null, "Client dispatcher was not set, thread groups have to be set instead", bossThreadGroupJmxAttribute);
84             checkCondition(getWorkerThreadGroup() != null, "Client dispatcher was not set, thread groups have to be set instead", workerThreadGroupJmxAttribute);
85         }
86
87         // Check username + password in case of ssh
88         if(getTcpOnly() == false) {
89             checkNotNull(getUsername(), usernameJmxAttribute);
90             checkNotNull(getPassword(), passwordJmxAttribute);
91         }
92
93     }
94
95     @Override
96     public java.lang.AutoCloseable createInstance() {
97         ServiceReference<DataProviderService> serviceReference = bundleContext.getServiceReference(DataProviderService.class);
98
99         DataProviderService dataProviderService =
100                 bundleContext.getService(serviceReference);
101
102         getDomRegistryDependency();
103         NetconfDevice device = new NetconfDevice(getIdentifier().getInstanceName());
104
105         device.setClientConfig(getClientConfig(device));
106
107         device.setProcessingExecutor(getGlobalProcessingExecutor());
108
109         device.setEventExecutor(getEventExecutorDependency());
110         device.setDispatcher(getClientDispatcher() == null ? createDispatcher() : getClientDispatcherDependency());
111         device.setSchemaSourceProvider(getGlobalNetconfSchemaProvider(bundleContext));
112         device.setDataProviderService(dataProviderService);
113         getDomRegistryDependency().registerProvider(device, bundleContext);
114         device.start();
115         return device;
116     }
117
118     private ExecutorService getGlobalProcessingExecutor() {
119         return GLOBAL_PROCESSING_EXECUTOR == null ? Executors.newCachedThreadPool() : GLOBAL_PROCESSING_EXECUTOR;
120     }
121
122     private synchronized AbstractCachingSchemaSourceProvider<String, InputStream> getGlobalNetconfSchemaProvider(BundleContext bundleContext) {
123         if(GLOBAL_NETCONF_SOURCE_PROVIDER == null) {
124             String storageFile = "cache/schema";
125             //            File directory = bundleContext.getDataFile(storageFile);
126             File directory = new File(storageFile);
127             SchemaSourceProvider<String> defaultProvider = SchemaSourceProviders.noopProvider();
128             GLOBAL_NETCONF_SOURCE_PROVIDER = FilesystemSchemaCachingProvider.createFromStringSourceProvider(defaultProvider, directory);
129         }
130         return GLOBAL_NETCONF_SOURCE_PROVIDER;
131     }
132
133     // FIXME BUG-944 remove backwards compatibility
134     /**
135      * @deprecated Use getClientDispatcherDependency method instead to retrieve injected dispatcher.
136      * This one creates new instance of NetconfClientDispatcher and will be removed in near future.
137      */
138     @Deprecated
139     private NetconfClientDispatcher createDispatcher() {
140         return new NetconfClientDispatcherImpl(getBossThreadGroupDependency(), getWorkerThreadGroupDependency(), new HashedWheelTimer());
141     }
142
143     public void setBundleContext(BundleContext bundleContext) {
144         this.bundleContext = bundleContext;
145     }
146
147     public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDevice device) {
148         InetSocketAddress socketAddress = getSocketAddress();
149         ReconnectStrategy strategy = getReconnectStrategy();
150         long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
151
152         return NetconfReconnectingClientConfigurationBuilder.create()
153         .withAddress(socketAddress)
154         .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
155         .withReconnectStrategy(strategy)
156         .withSessionListener(new NetconfDeviceListener(device))
157         .withAuthHandler(new LoginPassword(getUsername(),getPassword()))
158         .withProtocol(getTcpOnly() ?
159                 NetconfClientConfiguration.NetconfClientProtocol.TCP :
160                 NetconfClientConfiguration.NetconfClientProtocol.SSH)
161         .withConnectStrategyFactory(new ReconnectStrategyFactory() {
162             @Override
163             public ReconnectStrategy createReconnectStrategy() {
164                 return getReconnectStrategy();
165             }
166         })
167         .build();
168     }
169
170     private ReconnectStrategy getReconnectStrategy() {
171         Long connectionAttempts;
172         if (getMaxConnectionAttempts() != null && getMaxConnectionAttempts() > 0) {
173             connectionAttempts = getMaxConnectionAttempts();
174         } else {
175             logger.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
176             connectionAttempts = null;
177         }
178         double sleepFactor = 1.5;
179         int minSleep = 1000;
180         Long maxSleep = null;
181         Long deadline = null;
182
183         return new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, getBetweenAttemptsTimeoutMillis(),
184                 minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
185     }
186
187     private InetSocketAddress getSocketAddress() {
188         /*
189          * Uncomment after Switch to IP Address
190         if(getAddress().getIpv4Address() != null) {
191             addressValue = getAddress().getIpv4Address().getValue();
192         } else {
193             addressValue = getAddress().getIpv6Address().getValue();
194         }
195          */
196         InetAddress inetAddress = InetAddresses.forString(getAddress());
197         return new InetSocketAddress(inetAddress, getPort().intValue());
198     }
199 }