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