2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
20 * ============LICENSE_END=========================================================
23 package org.onap.ccsdk.sli.adaptors.ansible.impl;
25 import com.att.eelf.configuration.EELFLogger;
26 import com.att.eelf.configuration.EELFManager;
27 import java.io.Closeable;
28 import java.io.FileInputStream;
29 import java.io.IOException;
30 import java.security.KeyManagementException;
31 import java.security.KeyStore;
32 import java.security.KeyStoreException;
33 import java.security.NoSuchAlgorithmException;
34 import java.security.cert.CertificateException;
35 import java.security.cert.CertificateFactory;
36 import java.security.cert.X509Certificate;
37 import javax.net.ssl.SSLContext;
38 import org.apache.commons.lang.StringUtils;
39 import org.apache.http.HttpEntity;
40 import org.apache.http.HttpResponse;
41 import org.apache.http.auth.AuthScope;
42 import org.apache.http.auth.UsernamePasswordCredentials;
43 import org.apache.http.client.config.RequestConfig;
44 import org.apache.http.client.methods.HttpGet;
45 import org.apache.http.client.methods.HttpPost;
46 import org.apache.http.client.protocol.HttpClientContext;
47 import org.apache.http.conn.ssl.NoopHostnameVerifier;
48 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
49 import org.apache.http.conn.ssl.SSLContexts;
50 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
51 import org.apache.http.entity.StringEntity;
52 import org.apache.http.impl.client.BasicCredentialsProvider;
53 import org.apache.http.impl.client.CloseableHttpClient;
54 import org.apache.http.impl.client.HttpClients;
55 import org.apache.http.util.EntityUtils;
56 import org.json.JSONObject;
57 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult;
58 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResultCodes;
59 import org.onap.ccsdk.sli.core.utils.PathValidator;
62 * Returns a custom http client
64 * - can create one with ssl using an X509 certificate that does NOT have a known CA
65 * - create one which trusts ALL SSL certificates
66 * - return default httpclient (which only trusts known CAs from default cacerts file for process) this is the default
70 public class ConnectionBuilder implements Closeable {
71 private static final String STATUS_CODE_KEY = "StatusCode";
72 private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class);
74 private final CloseableHttpClient httpClient;
75 private final HttpClientContext httpContext = new HttpClientContext();
78 * Constructor that initializes an http client based on certificate
80 public ConnectionBuilder(String certFile, int timeout) throws KeyStoreException, CertificateException, IOException,
81 KeyManagementException, NoSuchAlgorithmException {
83 /* Point to the certificate */
84 try (FileInputStream fs = new FileInputStream(certFile)) {
85 /* Generate a certificate from the X509 */
86 CertificateFactory cf = CertificateFactory.getInstance("X.509");
87 X509Certificate cert = (X509Certificate) cf.generateCertificate(fs);
89 /* Create a keystore object and load the certificate there */
90 KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
91 keystore.load(null, null);
92 keystore.setCertificateEntry("cacert", cert);
94 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
95 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
96 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
98 RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build();
99 httpClient = HttpClients.custom().setDefaultRequestConfig(config).setSSLSocketFactory(factory).build();
104 * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS
107 public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd, int timeout, String serverIP)
108 throws KeyStoreException, IOException, KeyManagementException, NoSuchAlgorithmException,
109 CertificateException {
110 if (!PathValidator.isValidFilePath(trustStoreFile)) {
111 throw new IOException("Invalid trust store file path");
114 /* Load the specified trustStore */
115 KeyStore keystore = KeyStore.getInstance("JKS");
116 FileInputStream readStream = new FileInputStream(trustStoreFile);
117 keystore.load(readStream, trustStorePasswd);
118 if (StringUtils.isNotBlank(serverIP)) {
119 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
120 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier());
122 RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build();
123 httpClient = HttpClients.custom().setDefaultRequestConfig(config).setSSLSocketFactory(factory).build();
125 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
126 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
127 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
128 RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build();
129 httpClient = HttpClients.custom().setDefaultRequestConfig(config).setSSLSocketFactory(factory).build();
134 * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1 or
135 * Default if Mode == 0
137 public ConnectionBuilder(int mode, int timeout)
138 throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
139 RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build();
141 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
142 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
143 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
145 httpClient = HttpClients.custom().setDefaultRequestConfig(config).setSSLSocketFactory(factory).build();
147 httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
151 // Use to create an http context with auth headers
152 public void setHttpContext(String user, String pswd) {
154 // Are credential provided ? If so, set the context to be used
155 if (user != null && !user.isEmpty() && pswd != null && !pswd.isEmpty()) {
156 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pswd);
157 AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
158 BasicCredentialsProvider credsprovider = new BasicCredentialsProvider();
159 credsprovider.setCredentials(authscope, credentials);
160 httpContext.setCredentialsProvider(credsprovider);
164 // Method posts to the ansible server and writes out response to
165 // Ansible result object
166 public AnsibleResult post(String agentUrl, String payload) {
168 AnsibleResult result = new AnsibleResult();
171 HttpPost postObj = new HttpPost(agentUrl);
172 StringEntity bodyParams = new StringEntity(payload, "UTF-8");
173 postObj.setEntity(bodyParams);
174 postObj.addHeader("Content-type", "application/json");
176 HttpResponse response = httpClient.execute(postObj, httpContext);
177 HttpEntity entity = response.getEntity();
178 String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
179 int responseCode = response.getStatusLine().getStatusCode();
180 result.setStatusCode(responseCode);
181 result.setStatusMessage(responseOutput);
182 } catch (IOException io) {
183 logger.error("Caught IOException", io);
184 result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
185 result.setStatusMessage(io.getMessage());
190 // Method gets information from an Ansible server and writes out response to
191 // Ansible result object
193 public AnsibleResult get(String agentUrl) {
195 AnsibleResult result = new AnsibleResult();
198 HttpGet getObj = new HttpGet(agentUrl);
199 HttpResponse response = httpClient.execute(getObj, httpContext);
200 HttpEntity entity = response.getEntity();
201 String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
202 int responseCode = response.getStatusLine().getStatusCode();
203 logger.info("GetResult response for ansible GET URL" + agentUrl + " returned " + responseOutput);
204 JSONObject postResponse = new JSONObject(responseOutput);
205 if (postResponse.has(STATUS_CODE_KEY)) {
206 int codeStatus = postResponse.getInt(STATUS_CODE_KEY);
207 if (codeStatus == AnsibleResultCodes.PENDING.getValue()) {
208 result.setStatusCode(codeStatus);
210 result.setStatusCode(responseCode);
213 result.setStatusCode(responseCode);
215 result.setStatusMessage(responseOutput);
216 } catch (IOException io) {
217 result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
218 result.setStatusMessage(io.getMessage());
219 logger.error("Caught IOException", io);
225 public void close() {
227 if (httpClient != null) {
230 } catch (IOException e) {
231 logger.error("Caught IOException during httpClient close", e);