2 * Copyright 2018 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.alibaba.fastjson.JSON;
18 import com.alibaba.fastjson.JSONArray;
19 import com.alibaba.fastjson.JSONObject;
20 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
21 import org.onap.holmes.common.aai.config.AaiConfig;
22 import org.onap.holmes.common.config.MicroServiceConfig;
23 import org.onap.holmes.common.exception.CorrelationException;
25 import javax.ws.rs.client.Client;
26 import javax.ws.rs.client.ClientBuilder;
27 import javax.ws.rs.client.Entity;
28 import javax.ws.rs.client.WebTarget;
29 import javax.ws.rs.core.MultivaluedHashMap;
30 import javax.ws.rs.core.MultivaluedMap;
31 import javax.ws.rs.core.Response;
32 import java.util.HashMap;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
37 import lombok.extern.slf4j.Slf4j;
40 public class AaiQuery4Ccvpn {
42 private MultivaluedMap<String, Object> headers;
44 public static AaiQuery4Ccvpn newInstance() {
45 return new AaiQuery4Ccvpn();
48 private static final String EMPTY_STR = "";
50 private static final JSONObject EMPTY_JSON = new JSONObject();
52 private AaiQuery4Ccvpn() {
53 headers = new MultivaluedHashMap<>();
54 headers.add("X-TransactionId", AaiConfig.X_TRANSACTION_ID);
55 headers.add("X-FromAppId", AaiConfig.X_FROMAPP_ID);
56 headers.add("Authorization", AaiConfig.getAuthenticationCredentials());
57 headers.add("Accept", "application/json");
58 headers.add("Content-Type", "application/json");
62 * Query the logic link information for AAI. This method is based on the API:
63 * https://<AAI host>:<AAI port>/aai/v14/network/network-resources/network-resource/{networkId}/pnfs/pnf/{pnfName}/p-interfaces?interface-name={ifName}&operational-status={status}
70 * @return the ID of the logic link
72 public String getLogicLink(String networkId, String pnfName, String ifName, String status) throws CorrelationException {
73 Map<String, String> params = new HashMap<>();
74 params.put("networkId", networkId);
75 params.put("pnfName", pnfName);
76 params.put("ifName", ifName);
78 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_QUERY, params)
79 + (status == null ? "" : String.format("&operational-status=%s", status)));
80 JSONObject linkInfo = getInfo(response.readEntity(String.class), "p-interface", "logical-link");
81 if (linkInfo == null) {
82 log.warn(String.format("Link information is missing from AAI. Method: [getLogicLink], " +
83 "params: [networkId - %s, pnfName - %s, ifName - %s].", networkId, pnfName, ifName));
86 return extractValueFromJsonArray(linkInfo.getJSONArray("relationship-data"), "logical-link.link-name");
90 * Query the service instances related to a terminal point. This method is mainly based on the API:
91 * https://<AAI host>:<AAI port>/aai/v14/network/connectivities?connectivity-id={connectivityId}
93 * https://<AAI host>:<AAI port>/aai/v14/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription/{service-type}
94 * provided by AAI. The path for getting the required instance information is: p-interface → vpn-vpnbinding → connectivity → service instance
100 * @return service instances in JSONObject format
102 public JSONObject getServiceInstance(String networkId, String pnfName, String ifName, String status) {
104 JSONObject vpnBindingInfo = getVpnBindingInfo(networkId, pnfName, ifName, status);
105 if (vpnBindingInfo == null) {
106 log.warn(String.format("VPN binding information is missing from AAI. " +
107 "Method: [getServiceInstance], params: [networkId - %s, pnfName - %s, " +
108 "ifName - %s, status - %s].", networkId, pnfName, ifName, status));
111 String vpnBindingId = extractValueFromJsonArray(vpnBindingInfo.getJSONArray("relationship-data"),
112 "vpn-binding.vpn-id");
113 JSONObject connectivityInfo = getConnectivityInfo(vpnBindingId);
114 if (connectivityInfo == null) {
115 log.warn(String.format("Connectivity information is missing from AAI. " +
116 "Method: [getServiceInstance], params: [networkId - %s, pnfName - %s, " +
117 "ifName - %s, status - %s].", networkId, pnfName, ifName, status));
120 String connectivityId = extractValueFromJsonArray(connectivityInfo.getJSONArray("relationship-data"),
121 "connectivity.connectivity-id");
122 JSONObject serviceInstanceInfo = getServiceInstanceByConn(connectivityId);
123 if (serviceInstanceInfo == null) {
124 log.warn(String.format("Service instance information is missing from AAI. " +
125 "Method: [getServiceInstance], params: [networkId - %s, pnfName - %s, " +
126 "ifName - %s, status - %s].", networkId, pnfName, ifName, status));
129 String serviceInstancePath = serviceInstanceInfo.getString("related-link");
131 Response response = get(getHostAddr(), getPath(serviceInstancePath));
132 JSONObject instance = JSON.parseObject(response.readEntity(String.class));
134 String[] params = new String[2];
135 Pattern pattern = Pattern.compile("/aai/v\\d+/business/customers/customer/(.+)" +
136 "/service-subscriptions/service-subscription/(.+)" +
137 "/service-instances/service-instance/(.+)");
138 Matcher matcher = pattern.matcher(serviceInstancePath);
139 if (matcher.find()) {
140 params[0] = matcher.group(1);
141 params[1] = matcher.group(2);
143 instance.put("globalSubscriberId", params[0]);
144 instance.put("serviceType", params[1]);
146 } catch (CorrelationException e) {
147 throw new RuntimeException(e.getMessage(), e);
151 public void updateTerminalPointStatus(String networkId, String pnfName, String ifName,
152 Map<String, Object> body) throws CorrelationException {
153 Map<String, String> params = new HashMap<>();
154 params.put("networkId", networkId);
155 params.put("pnfName", pnfName);
156 params.put("ifName", ifName);
157 Response r = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params));
158 JSONObject jsonObject = JSONObject.parseObject(r.readEntity(String.class));
159 body.put("resource-version", jsonObject.get("resource-version").toString());
161 put(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params), body);
164 public void updateLogicLinkStatus(String linkName, Map<String, Object> body) throws CorrelationException {
165 Response r = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, "linkName", linkName));
166 JSONObject jsonObject = JSONObject.parseObject(r.readEntity(String.class));
167 body.put("resource-version", jsonObject.get("resource-version").toString());
168 body.put("link-type", jsonObject.get("link-type").toString());
169 put(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, "linkName", linkName), body);
172 private JSONObject getVpnBindingInfo(String networkId, String pnfName,
173 String ifName, String status) throws CorrelationException {
174 Map<String, String> params = new HashMap();
175 params.put("networkId", networkId);
176 params.put("pnfName", pnfName);
177 params.put("ifName", ifName);
178 params.put("status", status);
179 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_VPN_ADDR, params));
180 return getInfo(response.readEntity(String.class), "p-interface", "vpn-binding");
183 private JSONObject getConnectivityInfo(String vpnId) throws CorrelationException {
184 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_CONN_ADDR, "vpnId", vpnId));
185 return getInfo(response.readEntity(String.class), "vpn-binding", "connectivity");
188 private JSONObject getServiceInstanceByConn(String connectivityId) throws CorrelationException {
189 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCE_ADDR_4_CCVPN,
190 "connectivityId", connectivityId));
191 return getInfo(response.readEntity(String.class), "connectivity", "service-instance");
194 private JSONObject getServiceInstance(String globalCustomerId, String serviceType) throws CorrelationException {
195 Map<String, String> params = new HashMap();
196 params.put("global-customer-id", globalCustomerId);
197 params.put("service-type", serviceType);
198 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCES_ADDR_4_CCVPN, params));
199 return JSON.parseObject(response.readEntity(String.class));
202 private String getPath(String urlTemplate, Map<String, String> pathParams) {
203 String url = urlTemplate;
204 for (Map.Entry<String, String> entry : pathParams.entrySet()) {
205 url = url.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
210 private String getPath(String urlTemplate, String paramName, String paramValue) {
211 return urlTemplate.replaceAll("\\{" + paramName + "\\}", paramValue);
214 private String getPath(String serviceInstancePath) {
215 Pattern pattern = Pattern.compile("/aai/(v\\d+)/([A-Za-z0-9\\-]+[^/])(/*.*)");
216 Matcher matcher = pattern.matcher(serviceInstancePath);
218 if (matcher.find()) {
219 ret += "/aai-" + matcher.group(2) + "/" + matcher.group(1) + matcher.group(3);
225 private Response get(String host, String path) throws CorrelationException {
226 Client client = ClientBuilder.newClient();
227 WebTarget target = client.target(host).path(path);
229 Response response = target.request().headers(getAaiHeaders()).get();
230 if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
231 throw new CorrelationException("Failed to connect to AAI. \nCause: "
232 + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
233 + getErrorMsg(String.format("%s%s", host, path), null, response));
236 } catch (CorrelationException e) {
238 } catch (Exception e) {
239 throw new CorrelationException(e.getMessage() + "More info: "
240 + getErrorMsg(String.format("%s%s", host, path), null, null), e);
244 private void put(String host, String path, Map<String, Object> body) throws CorrelationException {
245 Client client = ClientBuilder.newClient();
246 WebTarget target = client.target(host).path(path);
248 Response response = target.request().headers(getAaiHeaders()).build("PUT", Entity.json(body))
249 .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true).invoke();
250 if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
251 throw new CorrelationException("Failed to connect to AAI. \nCause: "
252 + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
253 + getErrorMsg(String.format("%s%s", host, path), body, response));
255 } catch (CorrelationException e) {
257 } catch (Exception e) {
258 throw new CorrelationException(e.getMessage() + "More info: "
259 + getErrorMsg(String.format("%s%s", host, path), body, null), e);
263 private JSONObject getInfo(String response, String pField, String field) {
264 JSONObject jObject = JSONObject.parseObject(response);
265 JSONObject pInterface = extractJsonObject(jObject, pField);
266 if (pInterface == null) {
267 pInterface = jObject;
269 JSONObject relationshipList = extractJsonObject(pInterface, "relationship-list");
270 JSONArray relationShip = extractJsonArray(relationshipList, "relationship");
271 if (relationShip != null) {
272 for (int i = 0; i < relationShip.size(); ++i) {
273 final JSONObject object = relationShip.getJSONObject(i);
274 if (object.getString("related-to").equals(field)) {
282 private JSONObject extractJsonObject(JSONObject obj, String key) {
283 if (obj != null && key != null && obj.containsKey(key)) {
284 return obj.getJSONObject(key);
289 private JSONArray extractJsonArray(JSONObject obj, String key) {
290 if (obj != null && key != null && obj.containsKey(key)) {
291 return obj.getJSONArray(key);
296 private MultivaluedMap getAaiHeaders() {
300 private String getHostAddr() {
301 return MicroServiceConfig.getMsbServerAddrWithHttpPrefix();
304 private String extractValueFromJsonArray(JSONArray relationshipData, String keyName) {
305 if (relationshipData != null) {
306 for (int i = 0; i < relationshipData.size(); ++i) {
307 JSONObject item = relationshipData.getJSONObject(i);
308 if (item.getString("relationship-key").equals(keyName)) {
309 return item.getString("relationship-value");
316 private String getErrorMsg(String url, Map<String, Object> body, Response response) {
317 StringBuilder sb = new StringBuilder();
318 sb.append("Rerquest URL: ").append(url).append("\n");
319 sb.append("Request Header: ").append(JSONObject.toJSONString(headers)).append("\n");
321 sb.append("Request Body: ").append(JSONObject.toJSONString(body)).append("\n");
323 if (response != null) {
324 sb.append("Request Body: ").append(response.readEntity(String.class));
326 return sb.toString();