2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.controlloop.actor.so;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
27 import java.util.Optional;
28 import java.util.concurrent.CompletableFuture;
29 import java.util.concurrent.TimeUnit;
30 import java.util.function.Function;
31 import javax.ws.rs.core.MediaType;
32 import javax.ws.rs.core.Response;
34 import org.onap.aai.domain.yang.CloudRegion;
35 import org.onap.aai.domain.yang.GenericVnf;
36 import org.onap.aai.domain.yang.ServiceInstance;
37 import org.onap.aai.domain.yang.Tenant;
38 import org.onap.policy.aai.AaiConstants;
39 import org.onap.policy.aai.AaiCqResponse;
40 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
41 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
42 import org.onap.policy.common.utils.coder.Coder;
43 import org.onap.policy.common.utils.coder.CoderException;
44 import org.onap.policy.common.utils.coder.StandardCoder;
45 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
46 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
47 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
48 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
49 import org.onap.policy.controlloop.policy.PolicyResult;
50 import org.onap.policy.controlloop.policy.Target;
51 import org.onap.policy.so.SoCloudConfiguration;
52 import org.onap.policy.so.SoModelInfo;
53 import org.onap.policy.so.SoRequest;
54 import org.onap.policy.so.SoRequestInfo;
55 import org.onap.policy.so.SoRequestParameters;
56 import org.onap.policy.so.SoRequestStatus;
57 import org.onap.policy.so.SoResponse;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
62 * Superclass for SDNC Operators. Note: subclasses should invoke {@link #resetGetCount()}
63 * each time they issue an HTTP request.
65 public abstract class SoOperation extends HttpOperation<SoResponse> {
66 private static final Logger logger = LoggerFactory.getLogger(SoOperation.class);
67 private static final Coder coder = new StandardCoder();
69 public static final String PAYLOAD_KEY_VF_COUNT = "vfCount";
70 public static final String FAILED = "FAILED";
71 public static final String COMPLETE = "COMPLETE";
72 public static final int SO_RESPONSE_CODE = 999;
74 // fields within the policy payload
75 public static final String REQ_PARAM_NM = "requestParameters";
76 public static final String CONFIG_PARAM_NM = "configurationParameters";
78 private final SoConfig config;
80 // values extracted from the parameter Target
81 private final String modelCustomizationId;
82 private final String modelInvariantId;
83 private final String modelVersionId;
85 private final String vfCountKey;
88 * Number of "get" requests issued so far, on the current operation attempt.
95 * Constructs the object.
97 * @param params operation parameters
98 * @param config configuration for this operation
100 public SoOperation(ControlLoopOperationParams params, HttpConfig config) {
101 super(params, config, SoResponse.class);
102 this.config = (SoConfig) config;
104 verifyNotNull("Target information", params.getTarget());
106 this.modelCustomizationId = params.getTarget().getModelCustomizationId();
107 this.modelInvariantId = params.getTarget().getModelInvariantId();
108 this.modelVersionId = params.getTarget().getModelVersionId();
110 vfCountKey = SoConstants.VF_COUNT_PREFIX + "[" + modelCustomizationId + "][" + modelInvariantId + "]["
111 + modelVersionId + "]";
115 * Subclasses should invoke this before issuing their first HTTP request.
117 protected void resetGetCount() {
119 setSubRequestId(null);
123 * Validates that the parameters contain the required target information to extract
124 * the VF count from the custom query.
126 protected void validateTarget() {
127 verifyNotNull("modelCustomizationId", modelCustomizationId);
128 verifyNotNull("modelInvariantId", modelInvariantId);
129 verifyNotNull("modelVersionId", modelVersionId);
132 private void verifyNotNull(String type, Object value) {
134 throw new IllegalArgumentException("missing " + type + " for guard payload");
142 protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
143 return startGuardAsync();
149 * @return a future to cancel or await the VF Count
151 @SuppressWarnings("unchecked")
152 protected CompletableFuture<OperationOutcome> obtainVfCount() {
153 if (params.getContext().contains(vfCountKey)) {
154 // already have the VF count
158 // need custom query from which to extract the VF count
159 ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
160 .operation(AaiCqResponse.OPERATION).payload(null).retry(null).timeoutSec(null).build();
162 // run Custom Query and then extract the VF count
163 return sequence(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams), this::storeVfCount);
167 * Stores the VF count.
169 * @return {@code null}
171 private CompletableFuture<OperationOutcome> storeVfCount() {
172 if (!params.getContext().contains(vfCountKey)) {
173 AaiCqResponse cq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
174 int vfcount = cq.getVfModuleCount(modelCustomizationId, modelInvariantId, modelVersionId);
176 params.getContext().setProperty(vfCountKey, vfcount);
182 protected int getVfCount() {
183 return params.getContext().getProperty(vfCountKey);
186 protected void setVfCount(int vfCount) {
187 params.getContext().setProperty(vfCountKey, vfCount);
191 * If the response does not indicate that the request has been completed, then sleep a
192 * bit and issue a "get".
195 protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
196 Response rawResponse, SoResponse response) {
198 // see if the request has "completed", whether or not it was successful
199 if (rawResponse.getStatus() == 200) {
200 String requestState = getRequestState(response);
201 if (COMPLETE.equalsIgnoreCase(requestState)) {
202 extractSubRequestId(response);
203 successfulCompletion();
204 return CompletableFuture
205 .completedFuture(setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response));
208 if (FAILED.equalsIgnoreCase(requestState)) {
209 extractSubRequestId(response);
210 return CompletableFuture
211 .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
217 // need a request ID with which to query
218 if (getSubRequestId() == null && !extractSubRequestId(response)) {
219 throw new IllegalArgumentException("missing request ID in response");
222 // see if the limit for the number of "gets" has been reached
223 if (getCount++ >= getMaxGets()) {
224 logger.warn("{}: execeeded 'get' limit {} for {}", getFullName(), getMaxGets(), params.getRequestId());
225 setOutcome(outcome, PolicyResult.FAILURE_TIMEOUT);
226 outcome.setMessage(SO_RESPONSE_CODE + " " + outcome.getMessage());
227 return CompletableFuture.completedFuture(outcome);
230 // sleep and then perform a "get" operation
231 Function<Void, CompletableFuture<OperationOutcome>> doGet = unused -> issueGet(outcome);
232 return sleep(getWaitMsGet(), TimeUnit.MILLISECONDS).thenComposeAsync(doGet);
236 public void generateSubRequestId(int attempt) {
237 setSubRequestId(null);
240 private boolean extractSubRequestId(SoResponse response) {
241 if (response == null || response.getRequestReferences() == null
242 || response.getRequestReferences().getRequestId() == null) {
246 setSubRequestId(response.getRequestReferences().getRequestId());
251 * Invoked when a request completes successfully.
253 protected void successfulCompletion() {
258 * Issues a "get" request to see if the original request is complete yet.
260 * @param outcome outcome to be populated with the response
261 * @return a future that can be used to cancel the "get" request or await its response
263 private CompletableFuture<OperationOutcome> issueGet(OperationOutcome outcome) {
264 String path = getPathGet() + getSubRequestId();
265 String url = getClient().getBaseUrl() + path;
267 logger.debug("{}: 'get' count {} for {}", getFullName(), getCount, params.getRequestId());
269 logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
271 return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
275 * Gets the request state of a response.
277 * @param response response from which to get the state
278 * @return the request state of the response, or {@code null} if it does not exist
280 protected String getRequestState(SoResponse response) {
281 SoRequest request = response.getRequest();
282 if (request == null) {
286 SoRequestStatus status = request.getRequestStatus();
287 if (status == null) {
291 return status.getRequestState();
295 * Treats everything as a success, so we always go into
296 * {@link #postProcessResponse(OperationOutcome, String, Response, SoResponse)}.
299 protected boolean isSuccess(Response rawResponse, SoResponse response) {
304 * Prepends the message with the http status code.
307 public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse,
308 SoResponse response) {
310 // set default result and message
311 setOutcome(outcome, result);
313 outcome.setMessage(rawResponse.getStatus() + " " + outcome.getMessage());
317 protected SoModelInfo prepareSoModelInfo() {
318 Target target = params.getTarget();
319 if (target == null) {
320 throw new IllegalArgumentException("missing Target");
323 if (target.getModelCustomizationId() == null || target.getModelInvariantId() == null
324 || target.getModelName() == null || target.getModelVersion() == null
325 || target.getModelVersionId() == null) {
326 throw new IllegalArgumentException("missing VF Module model");
329 SoModelInfo soModelInfo = new SoModelInfo();
330 soModelInfo.setModelCustomizationId(target.getModelCustomizationId());
331 soModelInfo.setModelInvariantId(target.getModelInvariantId());
332 soModelInfo.setModelName(target.getModelName());
333 soModelInfo.setModelVersion(target.getModelVersion());
334 soModelInfo.setModelVersionId(target.getModelVersionId());
335 soModelInfo.setModelType("vfModule");
340 * Construct requestInfo for the SO requestDetails.
342 * @return SO request information
344 protected SoRequestInfo constructRequestInfo() {
345 SoRequestInfo soRequestInfo = new SoRequestInfo();
346 soRequestInfo.setSource("POLICY");
347 soRequestInfo.setSuppressRollback(false);
348 soRequestInfo.setRequestorId("policy");
349 return soRequestInfo;
353 * Builds the request parameters from the policy payload.
355 protected Optional<SoRequestParameters> buildRequestParameters() {
356 if (params.getPayload() == null) {
357 return Optional.empty();
360 Object data = params.getPayload().get(REQ_PARAM_NM);
362 return Optional.empty();
366 return Optional.of(coder.decode(data.toString(), SoRequestParameters.class));
367 } catch (CoderException e) {
368 throw new IllegalArgumentException("invalid payload value: " + REQ_PARAM_NM);
373 * Builds the configuration parameters from the policy payload.
375 protected Optional<List<Map<String, String>>> buildConfigurationParameters() {
376 if (params.getPayload() == null) {
377 return Optional.empty();
380 Object data = params.getPayload().get(CONFIG_PARAM_NM);
382 return Optional.empty();
386 @SuppressWarnings("unchecked")
387 List<Map<String, String>> result = coder.decode(data.toString(), ArrayList.class);
388 return Optional.of(result);
389 } catch (CoderException | RuntimeException e) {
390 throw new IllegalArgumentException("invalid payload value: " + CONFIG_PARAM_NM);
395 * Construct cloudConfiguration for the SO requestDetails. Overridden for custom
398 * @param tenantItem tenant item from A&AI named-query response
399 * @return SO cloud configuration
401 protected SoCloudConfiguration constructCloudConfigurationCq(Tenant tenantItem, CloudRegion cloudRegionItem) {
402 SoCloudConfiguration cloudConfiguration = new SoCloudConfiguration();
403 cloudConfiguration.setTenantId(tenantItem.getTenantId());
404 cloudConfiguration.setLcpCloudRegionId(cloudRegionItem.getCloudRegionId());
405 return cloudConfiguration;
409 * Create simple HTTP headers for unauthenticated requests to SO.
411 * @return the HTTP headers
413 protected Map<String, Object> createSimpleHeaders() {
414 Map<String, Object> headers = new HashMap<>();
415 headers.put("Accept", MediaType.APPLICATION_JSON);
420 * These methods extract data from the Custom Query and throw an
421 * IllegalArgumentException if the desired data item is not found.
424 protected GenericVnf getVnfItem(AaiCqResponse aaiCqResponse, SoModelInfo soModelInfo) {
425 GenericVnf vnf = aaiCqResponse.getGenericVnfByVfModuleModelInvariantId(soModelInfo.getModelInvariantId());
427 throw new IllegalArgumentException("missing generic VNF");
433 protected ServiceInstance getServiceInstance(AaiCqResponse aaiCqResponse) {
434 ServiceInstance vnfService = aaiCqResponse.getServiceInstance();
435 if (vnfService == null) {
436 throw new IllegalArgumentException("missing VNF Service Item");
442 protected Tenant getDefaultTenant(AaiCqResponse aaiCqResponse) {
443 Tenant tenant = aaiCqResponse.getDefaultTenant();
444 if (tenant == null) {
445 throw new IllegalArgumentException("missing Tenant Item");
451 protected CloudRegion getDefaultCloudRegion(AaiCqResponse aaiCqResponse) {
452 CloudRegion cloudRegion = aaiCqResponse.getDefaultCloudRegion();
453 if (cloudRegion == null) {
454 throw new IllegalArgumentException("missing Cloud Region");
460 // these may be overridden by junit tests
463 * Gets the wait time, in milliseconds, between "get" requests.
465 * @return the wait time, in milliseconds, between "get" requests
467 public long getWaitMsGet() {
468 return TimeUnit.MILLISECONDS.convert(getWaitSecGet(), TimeUnit.SECONDS);
471 public int getMaxGets() {
472 return config.getMaxGets();
475 public String getPathGet() {
476 return config.getPathGet();
479 public int getWaitSecGet() {
480 return config.getWaitSecGet();