bd6c9b54ca3500267ac41a5379060b5b0c59bcd4
[appc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22
23 package org.openecomp.appc.listener.demo.impl;
24
25 import java.io.IOException;
26 import java.io.UnsupportedEncodingException;
27 import java.net.MalformedURLException;
28 import java.net.Socket;
29 import java.net.URL;
30 import java.net.UnknownHostException;
31 import java.security.KeyManagementException;
32 import java.security.KeyStore;
33 import java.security.KeyStoreException;
34 import java.security.NoSuchAlgorithmException;
35 import java.security.UnrecoverableKeyException;
36 import java.security.cert.CertificateException;
37 import java.security.cert.X509Certificate;
38
39 import javax.net.ssl.SSLContext;
40 import javax.net.ssl.TrustManager;
41 import javax.net.ssl.X509TrustManager;
42
43 import org.apache.commons.codec.binary.Base64;
44 import org.apache.commons.io.IOUtils;
45 import org.apache.http.HttpResponse;
46 import org.apache.http.HttpVersion;
47 import org.apache.http.client.HttpClient;
48 import org.apache.http.client.methods.HttpPost;
49 import org.apache.http.conn.ClientConnectionManager;
50 import org.apache.http.conn.scheme.PlainSocketFactory;
51 import org.apache.http.conn.scheme.Scheme;
52 import org.apache.http.conn.scheme.SchemeRegistry;
53 import org.apache.http.conn.ssl.SSLSocketFactory;
54 import org.apache.http.entity.StringEntity;
55 import org.apache.http.impl.client.DefaultHttpClient;
56 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
57 import org.apache.http.params.BasicHttpParams;
58 import org.apache.http.params.HttpParams;
59 import org.apache.http.params.HttpProtocolParams;
60 import org.apache.http.protocol.HTTP;
61 import org.json.JSONObject;
62 import org.openecomp.appc.exceptions.APPCException;
63 import org.openecomp.appc.listener.demo.model.IncomingMessage;
64 import org.openecomp.appc.listener.util.Mapper;
65
66 import com.att.eelf.configuration.EELFLogger;
67 import com.att.eelf.configuration.EELFManager;
68
69 public class ProviderOperations {
70
71     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
72
73     private static URL url;
74
75     private static String basic_auth;
76
77     //@formatter:off
78     @SuppressWarnings("nls")
79     private final static String TEMPLATE = "{\"input\": {\"common-request-header\": {\"service-request-id\": \"%s\"},\"config-payload\": {\"config-url\": \"%s\",\"config-json\":\"%s\"}}}";
80     //@formatter:on 
81
82     /**
83      * Calls the AppcProvider to run a topology directed graph
84      * 
85      * @param msg
86      *            The incoming message to be run
87      * @return True if the result is success. Never returns false and throws an exception instead.
88      * @throws UnsupportedEncodingException
89      * @throws Exception
90      *             if there was a failure processing the request. The exception message is the failure reason.
91      */
92     @SuppressWarnings("nls")
93     public static boolean topologyDG(IncomingMessage msg) throws APPCException {
94         if (msg == null) {
95             throw new APPCException("Provided message was null");
96         }
97
98         HttpPost post = null;
99         try {
100             // Concatenate the "action" on the end of the URL
101             String path = url.getPath() + ":" + msg.getAction().getValue();
102             URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
103
104             post = new HttpPost(serviceUrl.toExternalForm());
105             post.setHeader("Content-Type", "application/json");
106             post.setHeader("Accept", "application/json");
107
108             // Set Auth
109             if (basic_auth != null) {
110                 post.setHeader("Authorization", "Basic " + basic_auth);
111             }
112
113             //String body = buildReqest(msg.getId(), msg.getUrl(), msg.getIdentityUrl());
114             String body = buildReqest(msg.getHeader().getRequestID(), msg.getPayload().getGenericVnfId(), msg.getPayload().getPgStreams());
115             StringEntity entity = new StringEntity(body);
116             entity.setContentType("application/json");
117             post.setEntity(new StringEntity(body));
118         } catch (UnsupportedEncodingException | MalformedURLException e) {
119             throw new APPCException(e);
120         }
121
122         HttpClient client = getHttpClient();
123
124         int httpCode = 0;
125         String respBody = null;
126         try {
127             HttpResponse response = client.execute(post);
128             httpCode = response.getStatusLine().getStatusCode();
129             respBody = IOUtils.toString(response.getEntity().getContent());
130         } catch (IOException e) {
131             throw new APPCException(e);
132         }
133
134         if (httpCode == 200 && respBody != null) {
135             JSONObject json;
136             try {
137                 json = Mapper.toJsonObject(respBody);
138             } catch (Exception e) {
139                 LOG.error("Error prcoessing response from provider. Could not map response to json", e);
140                 throw new APPCException("APPC has an unknown RPC error");
141             }
142             boolean success;
143             String reason;
144             try {
145                 JSONObject header = json.getJSONObject("output").getJSONObject("common-response-header");
146                 success = header.getBoolean("success");
147                 reason = header.getString("reason");
148             } catch (Exception e) {
149                 LOG.error("Unknown error prcoessing failed response from provider. Json not in expected format", e);
150                 throw new APPCException("APPC has an unknown RPC error");
151             }
152             if (success) {
153                 return true;
154             }
155             String reasonStr = reason == null ? "Unknown" : reason;
156             LOG.warn(String.format("Topology Operation [%s] failed. Reason: %s", msg.getHeader().getRequestID(), reasonStr));
157             throw new APPCException(reasonStr);
158
159         }
160         throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
161     }
162
163     /**
164      * Updates the static var URL and returns the value;
165      * 
166      * @return The new value of URL
167      */
168     public static String getUrl() {
169         return url.toExternalForm();
170     }
171
172     public static void setUrl(String newUrl) {
173         try {
174             url = new URL(newUrl);
175         } catch (MalformedURLException e) {
176             e.printStackTrace();
177         }
178     }
179
180     /**
181      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
182      * to null
183      *
184      * @param user
185      *            The user with optional domain name
186      * @param password
187      *            The password for the user
188      * @return The new value of the basic auth string that will be used in the request headers
189      */
190     public static String setAuthentication(String user, String password) {
191         if (user != null && password != null) {
192             String authStr = user + ":" + password;
193             basic_auth = new String(Base64.encodeBase64(authStr.getBytes()));
194         } else {
195             basic_auth = null;
196         }
197         return basic_auth;
198     }
199
200     /**
201      * Builds the request body for a topology operation
202      * 
203      * @param id
204      *            The request id
205      * @param url
206      *            The vm's url
207      *            
208      * @param pgstreams 
209      *           The streams to send to the traffic generator
210      *
211      * @return A String containing the request body
212      */
213     private static String buildReqest(String id, String url, String pgstreams) {
214
215         return String.format(TEMPLATE, id, url, pgstreams);
216     }
217
218     @SuppressWarnings("deprecation")
219     private static HttpClient getHttpClient() throws APPCException {
220         HttpClient client;
221         if (url.getProtocol().equals("https")) {
222             try {
223                 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
224                 trustStore.load(null, null);
225                 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
226                 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
227
228                 HttpParams params = new BasicHttpParams();
229                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
230                 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
231
232                 SchemeRegistry registry = new SchemeRegistry();
233                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
234                 registry.register(new Scheme("https", sf, 443));
235                 registry.register(new Scheme("https", sf, 8443));
236                 registry.register(new Scheme("http", sf, 8181));
237
238                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
239                 client = new DefaultHttpClient(ccm, params);
240             } catch (Exception e) {
241                 client = new DefaultHttpClient();
242             }
243         } else if (url.getProtocol().equals("http")) {
244             client = new DefaultHttpClient();
245         } else {
246             throw new APPCException(
247                 "The provider.topology.url property is invalid. The url did not start with http[s]");
248         }
249         return client;
250     }
251
252     @SuppressWarnings("deprecation")
253     public static class MySSLSocketFactory extends SSLSocketFactory {
254         private SSLContext sslContext = SSLContext.getInstance("TLS");
255
256         public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
257                         KeyStoreException, UnrecoverableKeyException {
258             super(truststore);
259
260             TrustManager tm = new X509TrustManager() {
261                 @Override
262                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
263                 }
264
265                 @Override
266                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
267                 }
268
269                 @Override
270                 public X509Certificate[] getAcceptedIssuers() {
271                     return null;
272                 }
273             };
274
275             sslContext.init(null, new TrustManager[] {
276                 tm
277             }, null);
278         }
279
280         @Override
281         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
282             throws IOException, UnknownHostException {
283             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
284         }
285
286         @Override
287         public Socket createSocket() throws IOException {
288             return sslContext.getSocketFactory().createSocket();
289         }
290     }
291
292 }