Include response in OperationOutcome
[policy/models.git] / models-interactions / model-actors / actor.vfc / src / main / java / org / onap / policy / controlloop / actor / vfc / VfcOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.policy.controlloop.actor.vfc;
22
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;
27 import lombok.Getter;
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;
44
45 public abstract class VfcOperation extends HttpOperation<VfcResponse> {
46     private static final Logger logger = LoggerFactory.getLogger(VfcOperation.class);
47
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";
52
53     public static final String REQ_PARAM_NM = "requestParameters";
54     public static final String CONFIG_PARAM_NM = "configurationParameters";
55
56     private final VfcConfig config;
57
58     /**
59      * Number of "get" requests issued so far, on the current operation attempt.
60      */
61     @Getter
62     private int getCount;
63
64     /**
65      * Constructs the object.
66      *
67      * @param params operation parameters
68      * @param config configuration for this operation
69      */
70     public VfcOperation(ControlLoopOperationParams params, HttpConfig config) {
71         super(params, config, VfcResponse.class);
72         this.config = (VfcConfig) config;
73     }
74
75     /**
76      * Subclasses should invoke this before issuing their first HTTP request.
77      */
78     protected void resetGetCount() {
79         getCount = 0;
80     }
81
82     /**
83      * Starts the GUARD.
84      */
85     @Override
86     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
87         return startGuardAsync();
88     }
89
90     /**
91      * If the response does not indicate that the request has been completed, then sleep a
92      * bit and issue a "get".
93      */
94     @Override
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));
103             }
104
105             if ("error".equalsIgnoreCase(requestState)) {
106                 return CompletableFuture
107                         .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
108             }
109         }
110
111         // still incomplete
112
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");
116         }
117
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);
125         }
126
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);
130     }
131
132     /**
133      * Issues a "get" request to see if the original request is complete yet.
134      *
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
138      */
139     private CompletableFuture<OperationOutcome> issueGet(OperationOutcome outcome, VfcResponse response) {
140         String path = getPathGet() + response.getJobId();
141         String url = getClient().getBaseUrl() + path;
142
143         logger.debug("{}: 'get' count {} for {}", getFullName(), getCount, params.getRequestId());
144
145         logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
146
147         return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
148     }
149
150     /**
151      * Gets the request state of a response.
152      *
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
155      */
156     protected String getRequestState(VfcResponse response) {
157         if (response == null || response.getResponseDescriptor() == null
158                 || StringUtils.isBlank(response.getResponseDescriptor().getStatus())) {
159             return null;
160         }
161         return response.getResponseDescriptor().getStatus();
162     }
163
164     /**
165      * Treats everything as a success, so we always go into
166      * {@link #postProcessResponse(OperationOutcome, String, Response, SoResponse)}.
167      */
168     @Override
169     protected boolean isSuccess(Response rawResponse, VfcResponse response) {
170         return true;
171     }
172
173     /**
174      * Prepends the message with the http status code.
175      */
176     @Override
177     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse,
178             VfcResponse response) {
179
180         // set default result and message
181         setOutcome(outcome, result);
182
183         outcome.setResponse(response);
184         outcome.setMessage(rawResponse.getStatus() + " " + outcome.getMessage());
185         return outcome;
186     }
187
188     /**
189      * Construct VfcRequestObject from the ControlLoopOperationParams.
190      *
191      * @return request
192      */
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");
198
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.");
202         }
203
204         VfcHealActionVmInfo vmActionInfo = new VfcHealActionVmInfo();
205         vmActionInfo.setVmid(vmId);
206         vmActionInfo.setVmname(vmName);
207
208         VfcHealAdditionalParams additionalParams = new VfcHealAdditionalParams();
209         additionalParams.setAction(getName());
210         additionalParams.setActionInfo(vmActionInfo);
211
212         VfcHealRequest healRequest = new VfcHealRequest();
213         healRequest.setVnfInstanceId(params.getContext().getEvent().getAai().get(GENERIC_VNF_ID));
214         healRequest.setCause(getName());
215         healRequest.setAdditionalParams(additionalParams);
216
217         VfcRequest request = new VfcRequest();
218         request.setHealRequest(healRequest);
219         request.setNsInstanceId(serviceInstance);
220         request.setRequestId(context.getEvent().getRequestId());
221
222         return request;
223     }
224
225     // These may be overridden by jUnit tests
226
227     /**
228      * Gets the wait time, in milliseconds, between "get" requests.
229      *
230      * @return the wait time, in milliseconds, between "get" requests
231      */
232     public long getWaitMsGet() {
233         return TimeUnit.MILLISECONDS.convert(getWaitSecGet(), TimeUnit.SECONDS);
234     }
235
236     public int getMaxGets() {
237         return config.getMaxGets();
238     }
239
240     public String getPathGet() {
241         return config.getPathGet();
242     }
243
244     public int getWaitSecGet() {
245         return config.getWaitSecGet();
246     }
247 }