Released Version 1.4.7
[holmes/common.git] / holmes-actions / src / main / java / org / onap / holmes / common / aai / AaiQuery4Ccvpn.java
1 /**
2  * Copyright 2018-2023 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.google.gson.JsonArray;
18 import com.google.gson.JsonObject;
19 import com.google.gson.JsonParser;
20 import jakarta.ws.rs.client.Entity;
21 import org.onap.holmes.common.aai.config.AaiConfig;
22 import org.onap.holmes.common.config.MicroServiceConfig;
23 import org.onap.holmes.common.utils.JerseyClient;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 import java.util.HashMap;
28 import java.util.Map;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
31
32 public class AaiQuery4Ccvpn {
33
34     private final Logger log = LoggerFactory.getLogger(AaiQuery4Ccvpn.class);
35
36     private Map<String, Object> headers;
37
38     public static AaiQuery4Ccvpn newInstance() {
39         return new AaiQuery4Ccvpn();
40     }
41
42     private static final String EMPTY_STR = "";
43
44     private static final JsonObject EMPTY_JSON = new JsonObject();
45
46     private AaiQuery4Ccvpn() {
47         headers = new HashMap<>();
48         headers.put("X-TransactionId", AaiConfig.X_TRANSACTION_ID);
49         headers.put("X-FromAppId", AaiConfig.X_FROMAPP_ID);
50         headers.put("Authorization", AaiConfig.getAuthenticationCredentials());
51         headers.put("Accept", "application/json");
52         headers.put("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) {
67         Map<String, String> params = new HashMap<>();
68         params.put("networkId", networkId);
69         params.put("pnfName", pnfName);
70         params.put("ifName", ifName);
71
72         String response = get(getPath(AaiConfig.AaiConsts.AAI_LINK_QUERY, params)
73                 + (status == null ? "" : String.format("&operational-status=%s", status)));
74
75         JsonObject linkInfo = getInfo(response, "p-interface", "logical-link");
76
77         if (linkInfo == null) {
78             log.warn(String.format("Link information is missing from AAI. Method: [getLogicLink], " +
79                     "params: [networkId - %s, pnfName - %s, ifName - %s].", networkId, pnfName, ifName));
80             return EMPTY_STR;
81         }
82         return extractValueFromJsonArray(linkInfo.get("relationship-data").getAsJsonArray(), "logical-link.link-name");
83     }
84
85     /**
86      * Query the service instances related to a terminal point. This method is mainly based on the API:
87      * https://<AAI host>:<AAI port>/aai/v14/network/connectivities?connectivity-id={connectivityId}
88      * and
89      * https://<AAI host>:<AAI port>/aai/v14/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription/{service-type}
90      * provided by AAI. The path for getting the required instance information is: p-interface → vpn-vpnbinding → connectivity → service instance
91      *
92      * @param networkId
93      * @param pnfName
94      * @param ifName
95      * @param status
96      * @return service instances in JSONObject format
97      */
98     public JsonObject getServiceInstance(String networkId, String pnfName, String ifName, String status) {
99         JsonObject vpnBindingInfo = getVpnBindingInfo(networkId, pnfName, ifName, status);
100         if (vpnBindingInfo == null) {
101             log.warn(String.format("VPN binding information is missing from AAI. " +
102                     "Method: [getServiceInstance], params: [networkId - %s, pnfName - %s, " +
103                     "ifName - %s, status - %s].", networkId, pnfName, ifName, status));
104             return EMPTY_JSON;
105         }
106         String vpnBindingId = extractValueFromJsonArray(vpnBindingInfo.get("relationship-data").getAsJsonArray(),
107                 "vpn-binding.vpn-id");
108         JsonObject connectivityInfo = getConnectivityInfo(vpnBindingId);
109         if (connectivityInfo == null) {
110             log.warn(String.format("Connectivity information is missing from AAI. " +
111                     "Method: [getServiceInstance], params: [networkId - %s, pnfName - %s, " +
112                     "ifName - %s, status - %s].", networkId, pnfName, ifName, status));
113             return EMPTY_JSON;
114         }
115         String connectivityId = extractValueFromJsonArray(connectivityInfo.get("relationship-data").getAsJsonArray(),
116                 "connectivity.connectivity-id");
117         JsonObject serviceInstanceInfo = getServiceInstanceByConn(connectivityId);
118         if (serviceInstanceInfo == null) {
119             log.warn(String.format("Service instance information is missing from AAI. " +
120                     "Method: [getServiceInstance], params: [networkId - %s, pnfName - %s, " +
121                     "ifName - %s, status - %s].", networkId, pnfName, ifName, status));
122             return EMPTY_JSON;
123         }
124         String serviceInstancePath = serviceInstanceInfo.get("related-link").getAsString();
125
126         String response = get(serviceInstancePath);
127         JsonObject instance = JsonParser.parseString(response).getAsJsonObject();
128
129         String[] params = new String[2];
130         Pattern pattern = Pattern.compile("/aai/v\\d+/business/customers/customer/(.+)" +
131                 "/service-subscriptions/service-subscription/(.+)" +
132                 "/service-instances/service-instance/(.+)");
133         Matcher matcher = pattern.matcher(serviceInstancePath);
134         if (matcher.find()) {
135             params[0] = matcher.group(1);
136             params[1] = matcher.group(2);
137         }
138         instance.addProperty("globalSubscriberId", params[0]);
139         instance.addProperty("serviceType", params[1]);
140         return instance;
141     }
142
143
144     public void updateTerminalPointStatus(String networkId, String pnfName, String ifName,
145                                           Map<String, Object> body) {
146         Map<String, String> params = new HashMap<>();
147         params.put("networkId", networkId);
148         params.put("pnfName", pnfName);
149         params.put("ifName", ifName);
150         String r = get(getPath(AaiConfig.AaiConsts.AAI_TP_UPDATE, params));
151         JsonObject jsonObject = JsonParser.parseString(r).getAsJsonObject();
152         body.put("resource-version", jsonObject.get("resource-version").toString());
153
154         put(getPath(AaiConfig.AaiConsts.AAI_TP_UPDATE, params), body);
155     }
156
157
158     public void updateLogicLinkStatus(String linkName, Map<String, Object> body) {
159         String r = get(getPath(AaiConfig.AaiConsts.AAI_LINK_UPDATE, "linkName", linkName));
160         JsonObject jsonObject = JsonParser.parseString(r).getAsJsonObject();
161         body.put("resource-version", jsonObject.get("resource-version").toString());
162         body.put("link-type", jsonObject.get("link-type").toString());
163         put(getPath(AaiConfig.AaiConsts.AAI_LINK_UPDATE, "linkName", linkName), body);
164     }
165
166     private JsonObject getVpnBindingInfo(String networkId, String pnfName,
167                                          String ifName, String status) {
168         Map<String, String> params = new HashMap();
169         params.put("networkId", networkId);
170         params.put("pnfName", pnfName);
171         params.put("ifName", ifName);
172         params.put("status", status);
173         String response = get(getPath(AaiConfig.AaiConsts.AAI_VPN_ADDR, params));
174         return getInfo(response, "p-interface", "vpn-binding");
175     }
176
177     private JsonObject getConnectivityInfo(String vpnId) {
178         String response = get(getPath(AaiConfig.AaiConsts.AAI_CONN_ADDR, "vpnId", vpnId));
179         return getInfo(response, "vpn-binding", "connectivity");
180     }
181
182     private JsonObject getServiceInstanceByConn(String connectivityId) {
183         String response = get(getPath(AaiConfig.AaiConsts.AAI_SERVICE_INSTANCE_ADDR_4_CCVPN,
184                 "connectivityId", connectivityId));
185         return getInfo(response, "connectivity", "service-instance");
186     }
187
188     private String getPath(String urlTemplate, Map<String, String> pathParams) {
189         String url = urlTemplate;
190         for (Map.Entry<String, String> entry : pathParams.entrySet()) {
191             url = url.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
192         }
193         return url;
194     }
195
196     private String getPath(String urlTemplate, String paramName, String paramValue) {
197         return urlTemplate.replaceAll("\\{" + paramName + "\\}", paramValue);
198     }
199
200     private String getPath(String serviceInstancePath) {
201         Pattern pattern = Pattern.compile("/aai/(v\\d+)/([A-Za-z0-9\\-]+[^/])(/*.*)");
202         Matcher matcher = pattern.matcher(serviceInstancePath);
203         String ret = "/api";
204         if (matcher.find()) {
205             ret += "/aai-" + matcher.group(2) + "/" + matcher.group(1) + matcher.group(3);
206         }
207
208         return ret;
209     }
210
211     private JsonObject getInfo(String response, String pField, String field) {
212         JsonObject jObject = JsonParser.parseString(response).getAsJsonObject();
213         JsonObject pInterface = extractJsonObject(jObject, pField);
214         if (pInterface == null) {
215             pInterface = jObject;
216         }
217         JsonObject relationshipList = extractJsonObject(pInterface, "relationship-list");
218         JsonArray relationShip = extractJsonArray(relationshipList, "relationship");
219         if (relationShip != null) {
220             for (int i = 0; i < relationShip.size(); ++i) {
221                 final JsonObject object = relationShip.get(i).getAsJsonObject();
222                 if (object.get("related-to").getAsString().equals(field)) {
223                     return object;
224                 }
225             }
226         }
227         return null;
228     }
229
230     private JsonObject extractJsonObject(JsonObject obj, String key) {
231         if (obj != null && key != null && obj.has(key)) {
232             return obj.get(key).getAsJsonObject();
233         }
234         return null;
235     }
236
237     private JsonArray extractJsonArray(JsonObject obj, String key) {
238         if (obj != null && key != null && obj.has(key)) {
239             return obj.get(key).getAsJsonArray();
240         }
241         return null;
242     }
243
244     private String extractValueFromJsonArray(JsonArray relationshipData, String keyName) {
245         if (relationshipData != null) {
246             for (int i = 0; i < relationshipData.size(); ++i) {
247                 JsonObject item = relationshipData.get(i).getAsJsonObject();
248                 if (item.get("relationship-key").getAsString().equals(keyName)) {
249                     return item.get("relationship-value").getAsString();
250                 }
251             }
252         }
253         return null;
254     }
255
256     private String get(String path) {
257         return JerseyClient.newInstance().path(path).headers(headers).get(MicroServiceConfig.getAaiAddr());
258     }
259
260     private String put(String path, Map<String, Object> body) {
261         return JerseyClient.newInstance().path(path).headers(headers).put(MicroServiceConfig.getAaiAddr(), Entity.json(body));
262     }
263 }