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