2 * Copyright 2018-2020 ZTE Corporation.
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
7 * http://www.apache.org/licenses/LICENSE-2.0
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
15 package org.onap.holmes.common.aai;
17 import com.google.gson.Gson;
18 import com.google.gson.JsonArray;
19 import com.google.gson.JsonObject;
20 import com.google.gson.JsonParser;
21 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
22 import org.onap.holmes.common.aai.config.AaiConfig;
23 import org.onap.holmes.common.config.MicroServiceConfig;
24 import org.onap.holmes.common.exception.CorrelationException;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
28 import javax.ws.rs.client.Client;
29 import javax.ws.rs.client.ClientBuilder;
30 import javax.ws.rs.client.Entity;
31 import javax.ws.rs.client.WebTarget;
32 import javax.ws.rs.core.MultivaluedHashMap;
33 import javax.ws.rs.core.MultivaluedMap;
34 import javax.ws.rs.core.Response;
35 import java.util.HashMap;
37 import java.util.regex.Matcher;
38 import java.util.regex.Pattern;
40 public class AaiQuery4Ccvpn {
42 private final Logger log = LoggerFactory.getLogger(AaiQuery4Ccvpn.class);
44 private MultivaluedMap<String, Object> headers;
46 public static AaiQuery4Ccvpn newInstance() {
47 return new AaiQuery4Ccvpn();
50 private static final String EMPTY_STR = "";
52 private static final JsonObject EMPTY_JSON = new JsonObject();
54 private AaiQuery4Ccvpn() {
55 headers = new MultivaluedHashMap<>();
56 headers.add("X-TransactionId", AaiConfig.X_TRANSACTION_ID);
57 headers.add("X-FromAppId", AaiConfig.X_FROMAPP_ID);
58 headers.add("Authorization", AaiConfig.getAuthenticationCredentials());
59 headers.add("Accept", "application/json");
60 headers.add("Content-Type", "application/json");
64 * Query the logic link information for AAI. This method is based on the API:
65 * https://<AAI host>:<AAI port>/aai/v14/network/network-resources/network-resource/{networkId}/pnfs/pnf/{pnfName}/p-interfaces?interface-name={ifName}&operational-status={status}
72 * @return the ID of the logic link
74 public String getLogicLink(String networkId, String pnfName, String ifName, String status) throws CorrelationException {
75 Map<String, String> params = new HashMap<>();
76 params.put("networkId", networkId);
77 params.put("pnfName", pnfName);
78 params.put("ifName", ifName);
80 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_QUERY, params)
81 + (status == null ? "" : String.format("&operational-status=%s", status)));
82 JsonObject linkInfo = getInfo(response.readEntity(String.class), "p-interface", "logical-link");
83 if (linkInfo == null) {
84 log.warn(String.format("Link information is missing from AAI. Method: [getLogicLink], " +
85 "params: [networkId - %s, pnfName - %s, ifName - %s].", networkId, pnfName, ifName));
88 return extractValueFromJsonArray(linkInfo.get("relationship-data").getAsJsonArray(), "logical-link.link-name");
92 * Query the service instances related to a terminal point. This method is mainly based on the API:
93 * https://<AAI host>:<AAI port>/aai/v14/network/connectivities?connectivity-id={connectivityId}
95 * https://<AAI host>:<AAI port>/aai/v14/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription/{service-type}
96 * provided by AAI. The path for getting the required instance information is: p-interface → vpn-vpnbinding → connectivity → service instance
102 * @return service instances in JSONObject format
104 public JsonObject getServiceInstance(String networkId, String pnfName, String ifName, String status) {
106 JsonObject vpnBindingInfo = getVpnBindingInfo(networkId, pnfName, ifName, status);
107 if (vpnBindingInfo == null) {
108 log.warn(String.format("VPN binding information is missing from AAI. " +
109 "Method: [getServiceInstance], params: [networkId - %s, pnfName - %s, " +
110 "ifName - %s, status - %s].", networkId, pnfName, ifName, status));
113 String vpnBindingId = extractValueFromJsonArray(vpnBindingInfo.get("relationship-data").getAsJsonArray(),
114 "vpn-binding.vpn-id");
115 JsonObject connectivityInfo = getConnectivityInfo(vpnBindingId);
116 if (connectivityInfo == null) {
117 log.warn(String.format("Connectivity information is missing from AAI. " +
118 "Method: [getServiceInstance], params: [networkId - %s, pnfName - %s, " +
119 "ifName - %s, status - %s].", networkId, pnfName, ifName, status));
122 String connectivityId = extractValueFromJsonArray(connectivityInfo.get("relationship-data").getAsJsonArray(),
123 "connectivity.connectivity-id");
124 JsonObject serviceInstanceInfo = getServiceInstanceByConn(connectivityId);
125 if (serviceInstanceInfo == null) {
126 log.warn(String.format("Service instance information is missing from AAI. " +
127 "Method: [getServiceInstance], params: [networkId - %s, pnfName - %s, " +
128 "ifName - %s, status - %s].", networkId, pnfName, ifName, status));
131 String serviceInstancePath = serviceInstanceInfo.get("related-link").getAsString();
133 Response response = get(getHostAddr(), getPath(serviceInstancePath));
134 JsonObject instance = JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
136 String[] params = new String[2];
137 Pattern pattern = Pattern.compile("/aai/v\\d+/business/customers/customer/(.+)" +
138 "/service-subscriptions/service-subscription/(.+)" +
139 "/service-instances/service-instance/(.+)");
140 Matcher matcher = pattern.matcher(serviceInstancePath);
141 if (matcher.find()) {
142 params[0] = matcher.group(1);
143 params[1] = matcher.group(2);
145 instance.addProperty("globalSubscriberId", params[0]);
146 instance.addProperty("serviceType", params[1]);
148 } catch (CorrelationException e) {
149 throw new RuntimeException(e.getMessage(), e);
153 public void updateTerminalPointStatus(String networkId, String pnfName, String ifName,
154 Map<String, Object> body) throws CorrelationException {
155 Map<String, String> params = new HashMap<>();
156 params.put("networkId", networkId);
157 params.put("pnfName", pnfName);
158 params.put("ifName", ifName);
159 Response r = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params));
160 JsonObject jsonObject = JsonParser.parseString(r.readEntity(String.class)).getAsJsonObject();
161 body.put("resource-version", jsonObject.get("resource-version").toString());
163 put(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params), body);
166 public void updateLogicLinkStatus(String linkName, Map<String, Object> body) throws CorrelationException {
167 Response r = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, "linkName", linkName));
168 JsonObject jsonObject = JsonParser.parseString(r.readEntity(String.class)).getAsJsonObject();
169 body.put("resource-version", jsonObject.get("resource-version").toString());
170 body.put("link-type", jsonObject.get("link-type").toString());
171 put(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, "linkName", linkName), body);
174 private JsonObject getVpnBindingInfo(String networkId, String pnfName,
175 String ifName, String status) throws CorrelationException {
176 Map<String, String> params = new HashMap();
177 params.put("networkId", networkId);
178 params.put("pnfName", pnfName);
179 params.put("ifName", ifName);
180 params.put("status", status);
181 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_VPN_ADDR, params));
182 return getInfo(response.readEntity(String.class), "p-interface", "vpn-binding");
185 private JsonObject getConnectivityInfo(String vpnId) throws CorrelationException {
186 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_CONN_ADDR, "vpnId", vpnId));
187 return getInfo(response.readEntity(String.class), "vpn-binding", "connectivity");
190 private JsonObject getServiceInstanceByConn(String connectivityId) throws CorrelationException {
191 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCE_ADDR_4_CCVPN,
192 "connectivityId", connectivityId));
193 return getInfo(response.readEntity(String.class), "connectivity", "service-instance");
196 private JsonObject getServiceInstance(String globalCustomerId, String serviceType) throws CorrelationException {
197 Map<String, String> params = new HashMap();
198 params.put("global-customer-id", globalCustomerId);
199 params.put("service-type", serviceType);
200 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCES_ADDR_4_CCVPN, params));
201 return JsonParser.parseString(response.readEntity(String.class)).getAsJsonObject();
204 private String getPath(String urlTemplate, Map<String, String> pathParams) {
205 String url = urlTemplate;
206 for (Map.Entry<String, String> entry : pathParams.entrySet()) {
207 url = url.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
212 private String getPath(String urlTemplate, String paramName, String paramValue) {
213 return urlTemplate.replaceAll("\\{" + paramName + "\\}", paramValue);
216 private String getPath(String serviceInstancePath) {
217 Pattern pattern = Pattern.compile("/aai/(v\\d+)/([A-Za-z0-9\\-]+[^/])(/*.*)");
218 Matcher matcher = pattern.matcher(serviceInstancePath);
220 if (matcher.find()) {
221 ret += "/aai-" + matcher.group(2) + "/" + matcher.group(1) + matcher.group(3);
227 private Response get(String host, String path) throws CorrelationException {
228 Client client = ClientBuilder.newClient();
229 WebTarget target = client.target(host).path(path);
231 Response response = target.request().headers(getAaiHeaders()).get();
232 if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
233 throw new CorrelationException("Failed to connect to AAI. \nCause: "
234 + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
235 + getErrorMsg(String.format("%s%s", host, path), null, response));
238 } catch (CorrelationException e) {
240 } catch (Exception e) {
241 throw new CorrelationException(e.getMessage() + "More info: "
242 + getErrorMsg(String.format("%s%s", host, path), null, null), e);
246 private void put(String host, String path, Map<String, Object> body) throws CorrelationException {
247 Client client = ClientBuilder.newClient();
248 WebTarget target = client.target(host).path(path);
250 Response response = target.request().headers(getAaiHeaders()).build("PUT", Entity.json(body))
251 .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true).invoke();
252 if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
253 throw new CorrelationException("Failed to connect to AAI. \nCause: "
254 + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
255 + getErrorMsg(String.format("%s%s", host, path), body, response));
257 } catch (CorrelationException e) {
259 } catch (Exception e) {
260 throw new CorrelationException(e.getMessage() + "More info: "
261 + getErrorMsg(String.format("%s%s", host, path), body, null), e);
265 private JsonObject getInfo(String response, String pField, String field) {
266 JsonObject jObject = JsonParser.parseString(response).getAsJsonObject();
267 JsonObject pInterface = extractJsonObject(jObject, pField);
268 if (pInterface == null) {
269 pInterface = jObject;
271 JsonObject relationshipList = extractJsonObject(pInterface, "relationship-list");
272 JsonArray relationShip = extractJsonArray(relationshipList, "relationship");
273 if (relationShip != null) {
274 for (int i = 0; i < relationShip.size(); ++i) {
275 final JsonObject object = relationShip.get(i).getAsJsonObject();
276 if (object.get("related-to").getAsString().equals(field)) {
284 private JsonObject extractJsonObject(JsonObject obj, String key) {
285 if (obj != null && key != null && obj.has(key)) {
286 return obj.get(key).getAsJsonObject();
291 private JsonArray extractJsonArray(JsonObject obj, String key) {
292 if (obj != null && key != null && obj.has(key)) {
293 return obj.get(key).getAsJsonArray();
298 private MultivaluedMap getAaiHeaders() {
302 private String getHostAddr() {
303 return MicroServiceConfig.getMsbServerAddrWithHttpPrefix();
306 private String extractValueFromJsonArray(JsonArray relationshipData, String keyName) {
307 if (relationshipData != null) {
308 for (int i = 0; i < relationshipData.size(); ++i) {
309 JsonObject item = relationshipData.get(i).getAsJsonObject();
310 if (item.get("relationship-key").getAsString().equals(keyName)) {
311 return item.get("relationship-value").getAsString();
318 private String getErrorMsg(String url, Map<String, Object> body, Response response) {
319 Gson gson = new Gson();
320 StringBuilder sb = new StringBuilder();
321 sb.append("Rerquest URL: ").append(url).append("\n");
322 sb.append("Request Header: ").append(gson.toJson(headers)).append("\n");
324 sb.append("Request Body: ").append(gson.toJson(body)).append("\n");
326 if (response != null) {
327 sb.append("Request Body: ").append(response.readEntity(String.class));
329 return sb.toString();