d2208a35d0554024f7cd8cdffac47badc15f1d5f
[holmes/common.git] / holmes-actions / src / main / java / org / onap / holmes / common / aai / AaiQuery4Ccvpn.java
1 /**
2  * Copyright 2018 ZTE Corporation.
3  * <p>
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  * <p>
7  * http://www.apache.org/licenses/LICENSE-2.0
8  * <p>
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14
15 package org.onap.holmes.common.aai;
16
17 import com.alibaba.fastjson.JSONArray;
18 import com.alibaba.fastjson.JSONObject;
19 import org.onap.holmes.common.aai.config.AaiConfig;
20 import org.onap.holmes.common.config.MicroServiceConfig;
21 import org.onap.holmes.common.exception.CorrelationException;
22
23 import javax.ws.rs.client.Client;
24 import javax.ws.rs.client.ClientBuilder;
25 import javax.ws.rs.client.Entity;
26 import javax.ws.rs.client.WebTarget;
27 import javax.ws.rs.core.MultivaluedHashMap;
28 import javax.ws.rs.core.MultivaluedMap;
29 import javax.ws.rs.core.Response;
30
31 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
32
33 import java.util.HashMap;
34 import java.util.Map;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
37
38 public class AaiQuery4Ccvpn {
39
40     private MultivaluedMap<String, Object> headers;
41
42     static public AaiQuery4Ccvpn newInstance() {
43         return new AaiQuery4Ccvpn();
44     }
45
46     private AaiQuery4Ccvpn() {
47         headers = new MultivaluedHashMap<>();
48         headers.add("X-TransactionId", AaiConfig.X_TRANSACTION_ID);
49         headers.add("X-FromAppId", AaiConfig.X_FROMAPP_ID);
50         headers.add("Authorization", AaiConfig.getAuthenticationCredentials());
51         headers.add("Accept", "application/json");
52         headers.add("Content-Type", "application/json");
53     }
54
55     /**
56      * Query the logic link information for AAI. This method is based on the API:
57      * https://<AAI host>:<AAI port>/aai/v14/network/network-resources/network-resource/{networkId}/pnfs/pnf/{pnfName}/p-interfaces?interface-name={ifName}&operational-status={status}
58      * provided by AAI.
59      *
60      * @param networkId
61      * @param pnfName
62      * @param ifName
63      * @param status
64      * @return the ID of the logic link
65      */
66     public String getLogicLink(String networkId, String pnfName, String ifName, String status) throws CorrelationException {
67         Map<String, String> params = new HashMap<>();
68         params.put("networkId", networkId);
69         params.put("pnfName", pnfName);
70         params.put("ifName", ifName);
71
72         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_QUERY, params)
73                 + (status == null ? "" : String.format("&operational-status=%s", status)));
74         JSONObject linkInfo = getInfo(response.readEntity(String.class), "p-interface", "logical-link");
75         return extractValueFromJsonArray(linkInfo.getJSONArray("relationship-data"), "logical-link.link-name");
76     }
77
78     /**
79      * Query all the instances related to a terminal point. This method is mainly based on the API:
80      * https://<AAI host>:<AAI port>/aai/v14/network/connectivities?connectivity-id={connectivityId}
81      * and
82      * https://<AAI host>:<AAI port>/aai/v14/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription/{service-type}
83      * provided by AAI. The path for getting the required instance information is: p-interface → vpn-vpnbinding → connectivity → service instance
84      *
85      * @param networkId
86      * @param pnfName
87      * @param ifName
88      * @param status
89      * @return all related service instances in JSONArray format
90      */
91     public JSONArray getServiceInstances(String networkId, String pnfName, String ifName, String status) {
92         try {
93             JSONObject vpnBindingInfo = getVpnBindingInfo(networkId, pnfName, ifName, status);
94             String vpnBindingId = extractValueFromJsonArray(vpnBindingInfo.getJSONArray("relationship-data"),
95                     "vpn-binding.vpn-id");
96             JSONObject connectivityInfo = getConnectivityInfo(vpnBindingId);
97             String connectivityId = extractValueFromJsonArray(connectivityInfo.getJSONArray("relationship-data"),
98                                                               "connectivity.connectivity-id");
99             JSONObject serviceInstanceInfo = getServiceInstanceByConn(connectivityId);
100             String serviceInstancePath = serviceInstanceInfo.getString("related-link");
101             serviceInstancePath = serviceInstancePath.substring(0, serviceInstancePath.lastIndexOf('/'));
102
103             String[] params = new String[2];
104
105             Pattern pattern = Pattern.compile("/aai/v\\d+/business/customers/customer/(.+)/service-subscriptions/service-subscription/(.+)");
106             Matcher matcher = pattern.matcher(serviceInstancePath);
107             if (matcher.find()) {
108                 params[0] = matcher.group(1);
109                 params[1] = matcher.group(2);
110             }
111
112             Response response = get(getHostAddr(), getPath(serviceInstancePath));
113             JSONArray instances = getInstances(response.readEntity(String.class));
114             for (int i = 0; i < instances.size(); ++i) {
115                 JSONObject instance = instances.getJSONObject(i);
116                 Response res = get(getHostAddr(), serviceInstancePath + "/service-instances?service-instance-id="
117                         + instance.getString("service-instance-id"));
118                 String inputParams = JSONObject.parseObject(res.readEntity(String.class)).getString("input-parameters");
119                 instance.put("input-parameters", inputParams);
120                 instance.put("globalSubscriberId", params[0]);
121                 instance.put("serviceType", params[1]);
122             }
123
124             return instances;
125         } catch (CorrelationException e) {
126             throw new RuntimeException(e.getMessage(), e);
127         }
128     }
129
130     public void updateTerminalPointStatus(String networkId, String pnfName, String ifName,
131                                           Map<String, Object> body) throws CorrelationException {
132         Map<String, String> params = new HashMap<>();
133         params.put("networkId", networkId);
134         params.put("pnfName", pnfName);
135         params.put("ifName", ifName);
136         Response r = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params));
137         JSONObject jsonObject = JSONObject.parseObject(r.readEntity(String.class));
138         body.put("resource-version", jsonObject.get("resource-version").toString());
139
140         put(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params), body);
141     }
142
143     public void updateLogicLinkStatus(String linkName, Map<String, Object> body) throws CorrelationException {
144         Response r = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, "linkName", linkName));
145         JSONObject jsonObject = JSONObject.parseObject(r.readEntity(String.class));
146         body.put("resource-version", jsonObject.get("resource-version").toString());
147         put(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, "linkName", linkName), body);
148     }
149     private JSONObject getVpnBindingInfo(String networkId, String pnfName,
150                                          String ifName, String status) throws CorrelationException {
151         Map<String, String> params = new HashMap();
152         params.put("networkId", networkId);
153         params.put("pnfName", pnfName);
154         params.put("ifName", ifName);
155         params.put("status", status);
156         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_VPN_ADDR, params));
157         return getInfo(response.readEntity(String.class), "p-interface", "vpn-binding");
158     }
159
160     private JSONObject getConnectivityInfo(String vpnId) throws CorrelationException {
161         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_CONN_ADDR, "vpnId", vpnId));
162         return getInfo(response.readEntity(String.class), "vpn-binding", "connectivity");
163     }
164
165     private JSONObject getServiceInstanceByConn(String connectivityId) throws CorrelationException {
166         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCE_ADDR_4_CCVPN,
167                 "connectivityId", connectivityId));
168         return getInfo(response.readEntity(String.class), "connectivity", "service-instance");
169     }
170
171     private JSONArray getServiceInstances(String globalCustomerId, String serviceType) throws CorrelationException {
172         Map<String, String> params = new HashMap();
173         params.put("global-customer-id", globalCustomerId);
174         params.put("service-type", serviceType);
175         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCES_ADDR_4_CCVPN, params));
176         return getInstances(response.readEntity(String.class));
177     }
178
179     private String getPath(String urlTemplate, Map<String, String> pathParams) {
180         String url = urlTemplate;
181         for (String key : pathParams.keySet()) {
182             url = url.replaceAll("\\{" + key + "\\}", pathParams.get(key));
183         }
184         return url;
185     }
186
187     private String getPath(String urlTemplate, String paramName, String paramValue) {
188         return urlTemplate.replaceAll("\\{" + paramName + "\\}", paramValue);
189     }
190
191     private String getPath(String serviceInstancePath) {
192         Pattern pattern = Pattern.compile("/aai/(v\\d+)/([A-Za-z0-9\\-]+[^/])(/*.*)");
193         Matcher matcher = pattern.matcher(serviceInstancePath);
194         String ret = "/api";
195         if (matcher.find()) {
196             ret += "/aai-" + matcher.group(2) + "/" + matcher.group(1) + matcher.group(3);
197         }
198
199         return ret;
200     }
201
202     private Response get(String host, String path) throws CorrelationException {
203         Client client = ClientBuilder.newClient();
204         WebTarget target = client.target(host).path(path);
205         try {
206             Response response = target.request().headers(getAaiHeaders()).get();
207             if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
208                 throw new CorrelationException("Failed to connect to AAI. \nCause: "
209                         + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
210                         + getErrorMsg(String.format("%s%s", host, path), null, response));
211             }
212             return response;
213         } catch (CorrelationException e) {
214             throw e;
215         } catch (Exception e) {
216             throw new CorrelationException(e.getMessage() + "More info: "
217                     + getErrorMsg(String.format("%s%s", host, path), null, null), e);
218         }
219     }
220
221     private void put(String host, String path, Map<String, Object> body) throws CorrelationException {
222         Client client = ClientBuilder.newClient();
223         WebTarget target = client.target(host).path(path);
224         try {
225             Response response = target.request().headers(getAaiHeaders()).build("PUT", Entity.json(body))
226                     .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true).invoke();
227             if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
228                 throw new CorrelationException("Failed to connect to AAI. \nCause: "
229                         + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
230                         + getErrorMsg(String.format("%s%s", host, path), body, response));
231             }
232         } catch (CorrelationException e) {
233             throw e;
234         } catch (Exception e) {
235             throw new CorrelationException(e.getMessage() + "More info: "
236                     + getErrorMsg(String.format("%s%s", host, path), body, null), e);
237         }
238     }
239
240     private JSONObject getInfo(String response, String pField, String field) {
241         JSONObject jObject = JSONObject.parseObject(response);
242         JSONObject pInterface = extractJsonObject(jObject, pField);
243         if (pInterface == null) {
244             pInterface = jObject;
245         }
246         JSONObject relationshipList = extractJsonObject(pInterface, "relationship-list");
247         JSONArray relationShip = extractJsonArray(relationshipList, "relationship");
248         if (relationShip != null) {
249             for (int i = 0; i < relationShip.size(); ++i) {
250                 final JSONObject object = relationShip.getJSONObject(i);
251                 if (object.getString("related-to").equals(field)) {
252                     return object;
253                 }
254             }
255         }
256         return null;
257     }
258
259     private JSONArray getInstances(String response) {
260         JSONArray results = extractJsonArray(JSONObject.parseObject(response), "results");
261         JSONObject pInterface = extractJsonObject(results.getJSONObject(0), "service-subscription");
262         JSONObject serviceInstances = extractJsonObject(pInterface, "service-instances");
263         JSONArray instance = extractJsonArray(serviceInstances, "service-instance");
264         return instance;
265     }
266
267     private JSONObject extractJsonObject(JSONObject obj, String key) {
268         if (obj != null && key != null && obj.containsKey(key)) {
269             return obj.getJSONObject(key);
270         }
271         return null;
272     }
273
274     private JSONArray extractJsonArray(JSONObject obj, String key) {
275         if (obj != null && key != null && obj.containsKey(key)) {
276             return obj.getJSONArray(key);
277         }
278         return null;
279     }
280
281     private MultivaluedMap getAaiHeaders() {
282         return headers;
283     }
284
285     private String getHostAddr() {
286         return MicroServiceConfig.getMsbServerAddrWithHttpPrefix();
287     }
288
289     private String extractValueFromJsonArray(JSONArray relationshipData, String keyName) {
290         for (int i = 0; i < relationshipData.size(); ++i) {
291             JSONObject item = relationshipData.getJSONObject(i);
292             if (item.getString("relationship-key").equals(keyName)) {
293                 return item.getString("relationship-value");
294             }
295         }
296         return null;
297     }
298
299     private String getErrorMsg(String url, Map<String, Object> body, Response response) {
300         StringBuilder sb = new StringBuilder();
301         sb.append("Rerquest URL: ").append(url).append("\n");
302         sb.append("Request Header: ").append(JSONObject.toJSONString(headers)).append("\n");
303         if (body != null) {
304             sb.append("Request Body: ").append(JSONObject.toJSONString(body)).append("\n");
305         }
306         if (response != null) {
307             sb.append("Request Body: ").append(response.readEntity(String.class));
308         }
309         return sb.toString();
310     }
311 }