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.vfc;
23 import java.util.concurrent.CompletableFuture;
24 import java.util.concurrent.TimeUnit;
25 import java.util.function.Function;
26 import javax.ws.rs.core.Response;
28 import org.apache.commons.lang3.StringUtils;
29 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
30 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
31 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
32 import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
33 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
34 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
35 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
36 import org.onap.policy.controlloop.policy.PolicyResult;
37 import org.onap.policy.vfc.VfcHealActionVmInfo;
38 import org.onap.policy.vfc.VfcHealAdditionalParams;
39 import org.onap.policy.vfc.VfcHealRequest;
40 import org.onap.policy.vfc.VfcRequest;
41 import org.onap.policy.vfc.VfcResponse;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
45 public abstract class VfcOperation extends HttpOperation<VfcResponse> {
46 private static final Logger logger = LoggerFactory.getLogger(VfcOperation.class);
48 public static final String FAILED = "FAILED";
49 public static final String COMPLETE = "COMPLETE";
50 public static final int VFC_RESPONSE_CODE = 999;
51 public static final String GENERIC_VNF_ID = "generic-vnf.vnf-id";
53 public static final String REQ_PARAM_NM = "requestParameters";
54 public static final String CONFIG_PARAM_NM = "configurationParameters";
56 private final VfcConfig config;
59 * Number of "get" requests issued so far, on the current operation attempt.
65 * Constructs the object.
67 * @param params operation parameters
68 * @param config configuration for this operation
70 public VfcOperation(ControlLoopOperationParams params, HttpConfig config) {
71 super(params, config, VfcResponse.class);
72 this.config = (VfcConfig) config;
76 * Subclasses should invoke this before issuing their first HTTP request.
78 protected void resetGetCount() {
86 protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
87 return startGuardAsync();
91 * If the response does not indicate that the request has been completed, then sleep a
92 * bit and issue a "get".
95 protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
96 Response rawResponse, VfcResponse response) {
97 // Determine if the request has "completed" and determine if it was successful
98 if (rawResponse.getStatus() == 200) {
99 String requestState = getRequestState(response);
100 if ("finished".equalsIgnoreCase(requestState)) {
101 return CompletableFuture
102 .completedFuture(setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response));
105 if ("error".equalsIgnoreCase(requestState)) {
106 return CompletableFuture
107 .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
113 // need a request ID with which to query
114 if (response == null || response.getJobId() == null) {
115 throw new IllegalArgumentException("missing job ID in response");
118 // see if the limit for the number of "gets" has been reached
119 if (getCount++ >= getMaxGets()) {
120 logger.warn("{}: execeeded 'get' limit {} for {}", getFullName(), getMaxGets(), params.getRequestId());
121 setOutcome(outcome, PolicyResult.FAILURE_TIMEOUT);
122 outcome.setResponse(response);
123 outcome.setMessage(VFC_RESPONSE_CODE + " " + outcome.getMessage());
124 return CompletableFuture.completedFuture(outcome);
127 // sleep and then perform a "get" operation
128 Function<Void, CompletableFuture<OperationOutcome>> doGet = unused -> issueGet(outcome, response);
129 return sleep(getWaitMsGet(), TimeUnit.MILLISECONDS).thenComposeAsync(doGet);
133 * Issues a "get" request to see if the original request is complete yet.
135 * @param outcome outcome to be populated with the response
136 * @param response previous response
137 * @return a future that can be used to cancel the "get" request or await its response
139 private CompletableFuture<OperationOutcome> issueGet(OperationOutcome outcome, VfcResponse response) {
140 String path = getPathGet() + response.getJobId();
141 String url = getClient().getBaseUrl() + path;
143 logger.debug("{}: 'get' count {} for {}", getFullName(), getCount, params.getRequestId());
145 logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
147 return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
151 * Gets the request state of a response.
153 * @param response response from which to get the state
154 * @return the request state of the response, or {@code null} if it does not exist
156 protected String getRequestState(VfcResponse response) {
157 if (response == null || response.getResponseDescriptor() == null
158 || StringUtils.isBlank(response.getResponseDescriptor().getStatus())) {
161 return response.getResponseDescriptor().getStatus();
165 * Treats everything as a success, so we always go into
166 * {@link #postProcessResponse(OperationOutcome, String, Response, SoResponse)}.
169 protected boolean isSuccess(Response rawResponse, VfcResponse response) {
174 * Prepends the message with the http status code.
177 public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse,
178 VfcResponse response) {
180 // set default result and message
181 setOutcome(outcome, result);
183 outcome.setResponse(response);
184 outcome.setMessage(rawResponse.getStatus() + " " + outcome.getMessage());
189 * Construct VfcRequestObject from the ControlLoopOperationParams.
193 protected VfcRequest constructVfcRequest() {
194 ControlLoopEventContext context = params.getContext();
195 String serviceInstance = context.getEnrichment().get("service-instance.service-instance-id");
196 String vmId = context.getEnrichment().get("vserver.vserver-id");
197 String vmName = context.getEnrichment().get("vserver.vserver-name");
199 if (StringUtils.isBlank(serviceInstance) || StringUtils.isBlank(vmId) || StringUtils.isBlank(vmName)) {
200 throw new IllegalArgumentException(
201 "Cannot extract enrichment data for service instance, server id, or server name.");
204 VfcHealActionVmInfo vmActionInfo = new VfcHealActionVmInfo();
205 vmActionInfo.setVmid(vmId);
206 vmActionInfo.setVmname(vmName);
208 VfcHealAdditionalParams additionalParams = new VfcHealAdditionalParams();
209 additionalParams.setAction(getName());
210 additionalParams.setActionInfo(vmActionInfo);
212 VfcHealRequest healRequest = new VfcHealRequest();
213 healRequest.setVnfInstanceId(params.getContext().getEvent().getAai().get(GENERIC_VNF_ID));
214 healRequest.setCause(getName());
215 healRequest.setAdditionalParams(additionalParams);
217 VfcRequest request = new VfcRequest();
218 request.setHealRequest(healRequest);
219 request.setNsInstanceId(serviceInstance);
220 request.setRequestId(context.getEvent().getRequestId());
225 // These may be overridden by jUnit tests
228 * Gets the wait time, in milliseconds, between "get" requests.
230 * @return the wait time, in milliseconds, between "get" requests
232 public long getWaitMsGet() {
233 return TimeUnit.MILLISECONDS.convert(getWaitSecGet(), TimeUnit.SECONDS);
236 public int getMaxGets() {
237 return config.getMaxGets();
240 public String getPathGet() {
241 return config.getPathGet();
244 public int getWaitSecGet() {
245 return config.getWaitSecGet();