1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
|
/*-
* ============LICENSE_START=======================================================
* aai
* ================================================================================
* Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2019 Nordix Foundation.
* Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.policy.aai;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.json.JSONArray;
import org.json.JSONObject;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.rest.RestManager;
import org.onap.policy.rest.RestManager.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class handles communication towards and responses from A&AI for this module.
*/
public final class AaiManager {
// TODO remove this class
/** The Constant logger. */
private static final Logger logger = LoggerFactory.getLogger(AaiManager.class);
private static final String APPLICATION_JSON = "application/json";
private static final StandardCoder CODER = new StandardCoder();
// The REST manager used for processing REST calls for this AAI manager
private final RestManager restManager;
/** custom query and other AAI resource URLs. */
private static final String CQ_URL = "/aai/v16/query?format=resource";
private static final String TENANT_URL = "/aai/v16/search/nodes-query?"
+ "search-node-type=vserver&filter=vserver-name:EQUALS:";
private static final String PREFIX = "/aai/v16";
private static final String PNF_URL = PREFIX + "/network/pnfs/pnf/";
private static final String AAI_DEPTH_SUFFIX = "?depth=0";
/**
* Constructor, create the AAI manager with the specified REST manager.
*
* @param restManager the rest manager to use for REST calls
*/
public AaiManager(final RestManager restManager) {
this.restManager = restManager;
}
/**
* Creates the custom query payload from a tenant query response.
*
* @param getResponse response from the tenant query
* @return String Payload
*/
private String createCustomQueryPayload(String getResponse) {
if (getResponse == null) {
return null;
} else {
JSONObject responseObj = new JSONObject(getResponse);
JSONArray resultsArray;
if (responseObj.has("result-data")) {
resultsArray = (JSONArray) responseObj.get("result-data");
} else {
return null;
}
String resourceLink = resultsArray.getJSONObject(0).getString("resource-link");
String start = resourceLink.replace(PREFIX, "");
String query = "query/closed-loop";
JSONObject payload = new JSONObject();
payload.put("start", start);
payload.put("query", query);
return payload.toString();
}
}
/**
* This method is used to get the information for custom query.
*
* @param url url of the get method
* @param username Aai username
* @param password Aai password
* @param requestId request ID
* @param vserver Id of the vserver
* @return String
*/
private String getCustomQueryRequestPayload(String url, String username, String password, UUID requestId,
String vserver) {
String urlGet = url + TENANT_URL;
String getResponse = getStringQuery(urlGet, username, password, requestId, vserver);
return createCustomQueryPayload(getResponse);
}
/**
* Calls Aai and returns a custom query response for a vserver.
*
* @param url Aai url
* @param username Aai Username
* @param password Aai Password
* @param requestId request ID
* @param vserver Vserver
* @return AaiCqResponse response from Aai for custom query
*/
public AaiCqResponse getCustomQueryResponse(String url, String username, String password, UUID requestId,
String vserver) {
final Map<String, String> headers = createHeaders(requestId);
logger.debug("RestManager.put before");
String requestJson = getCustomQueryRequestPayload(url, username, password, requestId, vserver);
NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, requestJson);
url = url + CQ_URL;
Pair<Integer, String> httpDetails = this.restManager.put(url, username, password, headers, APPLICATION_JSON,
requestJson);
logger.debug("RestManager.put after");
if (httpDetails == null) {
NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "AAI POST Null Response");
logger.debug("AAI POST Null Response to {}", url);
return null;
}
int httpResponseCode = httpDetails.first;
NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "Response code: " + httpResponseCode);
NetLoggerUtil.getNetworkLogger().debug(httpDetails.second);
logger.debug(url);
logger.debug("{}", httpResponseCode);
logger.debug(httpDetails.second);
if (httpDetails.second != null) {
return new AaiCqResponse(httpDetails.second);
}
return null;
}
/**
* Returns the string response of a get query.
*
* @param url Aai URL
* @param username Aai Username
* @param password Aai Password
* @param requestId AaiRequestId
* @param key Aai Key
* @return String returns the string from the get query
*/
private String getStringQuery(final String url, final String username, final String password, final UUID requestId,
final String key) {
Map<String, String> headers = createHeaders(requestId);
String urlGet = url + key;
int attemptsLeft = 3;
while (attemptsLeft-- > 0) {
NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|]", CommInfrastructure.REST, urlGet);
Pair<Integer, String> httpDetailsGet = restManager.get(urlGet, username, password, headers);
if (httpDetailsGet == null) {
NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "AAI POST Null Response");
logger.debug("AAI GET Null Response to {}", urlGet);
return null;
}
int httpResponseCode = httpDetailsGet.first;
NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, "Response code: " + httpResponseCode);
NetLoggerUtil.getNetworkLogger().debug(httpDetailsGet.second);
logger.debug(urlGet);
logger.debug("{}", httpResponseCode);
logger.debug(httpDetailsGet.second);
if (httpResponseCode == 200 && httpDetailsGet.second != null) {
return httpDetailsGet.second;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
return null;
}
/**
* Create the headers for the HTTP request.
*
* @param requestId the request ID to insert in the headers
* @return the HTTP headers
*/
private Map<String, String> createHeaders(final UUID requestId) {
Map<String, String> headers = new HashMap<>();
headers.put("X-FromAppId", "POLICY");
headers.put("X-TransactionId", requestId.toString());
headers.put("Accept", APPLICATION_JSON);
return headers;
}
/**
* Perform a GET request for a particular PNF by PNF ID towards A&AI.
*
* @param url the A&AI URL
* @param username the user name for authentication
* @param password the password for authentication
* @param requestId the UUID of the request
* @param pnfName the AAI unique identifier for PNF object
* @return HashMap of PNF properties
*/
public Map<String, String> getPnf(String url, String username, String password, UUID requestId, String pnfName) {
String urlGet;
try {
urlGet = url + PNF_URL;
pnfName = URLEncoder.encode(pnfName, StandardCharsets.UTF_8.toString()) + AAI_DEPTH_SUFFIX;
} catch (UnsupportedEncodingException e) {
logger.error("Failed to encode the pnfName: {} using UTF-8", pnfName, e);
return null;
}
String responseGet = getStringQuery(urlGet, username, password, requestId, pnfName);
if (responseGet == null) {
logger.error("Null response from AAI for the url: {}.", urlGet);
return null;
}
try {
@SuppressWarnings("unchecked")
Map<String, String> pnfParams = CODER.decode(responseGet, HashMap.class);
// Map to AAI node.attribute notation
return pnfParams.entrySet().stream()
.collect(Collectors.toMap(e -> "pnf." + e.getKey(), Map.Entry::getValue));
} catch (CoderException e) {
logger.error("Failed to fetch PNF from AAI", e);
return null;
}
}
}
|