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