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
|
/*-
* ============LICENSE_START=======================================================
* so
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* 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.so;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import org.onap.policy.so.util.Serialization;
import org.onap.policy.drools.system.PolicyEngine;
import org.onap.policy.rest.RESTManager;
import org.onap.policy.rest.RESTManager.Pair;
import org.drools.core.WorkingMemory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
public final class SOManager {
private static final Logger logger = LoggerFactory.getLogger(SOManager.class);
private static final Logger netLogger = LoggerFactory.getLogger(org.onap.policy.drools.event.comm.Topic.NETWORK_LOGGER);
private static ExecutorService executors = Executors.newCachedThreadPool();
static final String MEDIA_TYPE = "application/json";
static final String LINE_SEPARATOR = System.lineSeparator();
// REST get timeout value in milliseconds
private static final long DEFAULT_GET_REQUEST_TIMEOUT = 20000;
// The REST manager used for processing REST calls for this VFC manager
private RESTManager restManager;
private long restGetTimeout = DEFAULT_GET_REQUEST_TIMEOUT;
public SOManager() {
restManager = new RESTManager();
}
public SOResponse createModuleInstance(String url, String urlBase, String username, String password, SORequest request) {
//
// Call REST
//
Map<String, String> headers = new HashMap<>();
headers.put("Accept", MEDIA_TYPE);
//
// 201 - CREATED - you are done just return
//
String requestJson = Serialization.gsonPretty.toJson(request);
netLogger.info("[OUT|{}|{}|{}|{}|{}|{}|]{}{}", "SO", url, username, password, headers, MEDIA_TYPE, LINE_SEPARATOR, requestJson);
Pair<Integer, String> httpDetails = restManager.post(url, username, password, headers, MEDIA_TYPE, requestJson);
if (httpDetails == null) {
return null;
}
if (httpDetails.a != 202) {
return null;
}
try {
SOResponse response = Serialization.gsonPretty.fromJson(httpDetails.b, SOResponse.class);
String body = Serialization.gsonPretty.toJson(response);
logger.debug("***** Response to post:");
logger.debug(body);
String requestId = response.getRequestReferences().getRequestId();
int attemptsLeft = 20;
String urlGet = urlBase + "/orchestrationRequests/v2/" + requestId;
SOResponse responseGet = null;
while (attemptsLeft-- > 0) {
Pair<Integer, String> httpDetailsGet = restManager.get(urlGet, username, password, headers);
if (httpDetailsGet == null) {
return null;
}
responseGet = Serialization.gsonPretty.fromJson(httpDetailsGet.b, SOResponse.class);
netLogger.info("[IN|{}|{}|]{}{}", "SO", urlGet, LINE_SEPARATOR, httpDetailsGet.b);
body = Serialization.gsonPretty.toJson(responseGet);
logger.debug("***** Response to get:");
logger.debug(body);
if (httpDetailsGet.a == 200 &&
(responseGet.getRequest().getRequestStatus().getRequestState().equalsIgnoreCase("COMPLETE")
|| responseGet.getRequest().getRequestStatus().getRequestState().equalsIgnoreCase("FAILED"))) {
logger.debug("***** ######## VF Module Creation {}",
responseGet.getRequest().getRequestStatus().getRequestState());
return responseGet;
}
Thread.sleep(restGetTimeout);
}
if (responseGet != null && responseGet.getRequest() != null
&& responseGet.getRequest().getRequestStatus() != null
&& responseGet.getRequest().getRequestStatus().getRequestState() != null) {
logger.warn("***** ######## VF Module Creation timeout. Status: ( {})",
responseGet.getRequest().getRequestStatus().getRequestState());
}
return responseGet;
}
catch (JsonSyntaxException e) {
logger.error("Failed to deserialize into SOResponse: ", e);
}
catch (InterruptedException e) {
logger.error("Interrupted exception: ", e);
Thread.currentThread().interrupt();
}
return null;
}
/**
*
* @param wm
* @param url
* @param urlBase
* @param username
* @param password
* @param request
*
* This method makes an asynchronous Rest call to MSO and inserts the response into the
* Drools working memory
* @return
*/
public Future<?> asyncSORestCall(String requestID, WorkingMemory wm, String serviceInstanceId, String vnfInstanceId, SORequest request) {
return executors.submit(new AsyncSORestCallThread(requestID, wm, serviceInstanceId, vnfInstanceId, request));
}
private class AsyncSORestCallThread implements Runnable {
final String requestID;
final WorkingMemory wm;
final String serviceInstanceId;
final String vnfInstanceId;
final SORequest request;
private AsyncSORestCallThread(final String requestID, final WorkingMemory wm, final String serviceInstanceId, final String vnfInstanceId, final SORequest request) {
this.requestID = requestID;
this.wm = wm;
this.serviceInstanceId = serviceInstanceId;
this.vnfInstanceId = vnfInstanceId;
this.request = request;
}
@Override
public void run() {
try {
String serverRoot = PolicyEngine.manager.getEnvironmentProperty("so.url");
String username = PolicyEngine.manager.getEnvironmentProperty("so.username");
String password = PolicyEngine.manager.getEnvironmentProperty("so.password");
String url = serverRoot + "/serviceInstances/v5/" + serviceInstanceId + "/vnfs/"
+ vnfInstanceId + "/vfModules";
String auth = username + ":" + password;
Map<String, String> headers = new HashMap<>();
byte[] encodedBytes = Base64.getEncoder().encode(auth.getBytes());
headers.put("Accept", MEDIA_TYPE);
headers.put("Authorization", "Basic " + new String(encodedBytes));
Gson gsonPretty =
new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create();
String soJson = gsonPretty.toJson(request);
SOResponse so = new SOResponse();
netLogger.info("[OUT|{}|{}|]{}{}", "SO", url, LINE_SEPARATOR, soJson);
Pair<Integer, String> httpResponse = restManager.post(url, "policy", "policy", headers, MEDIA_TYPE, soJson);
if (httpResponse != null) {
if (httpResponse.b != null && httpResponse.a != null) {
netLogger.info("[IN|{}|{}|]{}{}", url, "SO", LINE_SEPARATOR, httpResponse.b);
Gson gson = new Gson();
so = gson.fromJson(httpResponse.b, SOResponse.class);
so.setHttpResponseCode(httpResponse.a);
}
else {
logger.error("SO Response status/code is null.");
so.setHttpResponseCode(999);
}
}
else {
logger.error("SO Response returned null.");
so.setHttpResponseCode(999);
}
SOResponseWrapper soWrapper = new SOResponseWrapper(so, requestID);
wm.insert(soWrapper);
if (logger.isInfoEnabled()) {
logger.info("SOResponse inserted " + gsonPretty.toJson(soWrapper));
}
}
catch (Exception e) {
logger.error("Error while performing asyncSORestCall: " + e.getMessage(), e);
// create dummy SO object to trigger cleanup
SOResponse so = new SOResponse();
so.setHttpResponseCode(999);
wm.insert(so);
}
}
}
/**
* method to allow tuning of REST get timeout
* @param restGetTimeout the timeout value
*/
protected void setRestGetTimeout(final long restGetTimeout) {
this.restGetTimeout = restGetTimeout;
}
/**
* Protected setter for rest manager to allow mocked rest manager to be used for testing
* @param restManager the test REST manager
*/
protected void setRestManager(final RESTManager restManager) {
this.restManager = restManager;
}
}
|