Merge "Add VFC Actor"
[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.setMessage(VFC_RESPONSE_CODE + " " + outcome.getMessage());
123             return CompletableFuture.completedFuture(outcome);
124         }
125
126         // sleep and then perform a "get" operation
127         Function<Void, CompletableFuture<OperationOutcome>> doGet = unused -> issueGet(outcome, response);
128         return sleep(getWaitMsGet(), TimeUnit.MILLISECONDS).thenComposeAsync(doGet);
129     }
130
131     /**
132      * Issues a "get" request to see if the original request is complete yet.
133      *
134      * @param outcome outcome to be populated with the response
135      * @param response previous response
136      * @return a future that can be used to cancel the "get" request or await its response
137      */
138     private CompletableFuture<OperationOutcome> issueGet(OperationOutcome outcome, VfcResponse response) {
139         String path = getPathGet() + response.getJobId();
140         String url = getClient().getBaseUrl() + path;
141
142         logger.debug("{}: 'get' count {} for {}", getFullName(), getCount, params.getRequestId());
143
144         logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
145
146         return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
147     }
148
149     /**
150      * Gets the request state of a response.
151      *
152      * @param response response from which to get the state
153      * @return the request state of the response, or {@code null} if it does not exist
154      */
155     protected String getRequestState(VfcResponse response) {
156         if (response == null || response.getResponseDescriptor() == null
157                 || StringUtils.isBlank(response.getResponseDescriptor().getStatus())) {
158             return null;
159         }
160         return response.getResponseDescriptor().getStatus();
161     }
162
163     /**
164      * Treats everything as a success, so we always go into
165      * {@link #postProcessResponse(OperationOutcome, String, Response, SoResponse)}.
166      */
167     @Override
168     protected boolean isSuccess(Response rawResponse, VfcResponse response) {
169         return true;
170     }
171
172     /**
173      * Prepends the message with the http status code.
174      */
175     @Override
176     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse,
177             VfcResponse response) {
178
179         // set default result and message
180         setOutcome(outcome, result);
181
182         outcome.setMessage(rawResponse.getStatus() + " " + outcome.getMessage());
183         return outcome;
184     }
185
186     /**
187      * Construct VfcRequestObject from the ControlLoopOperationParams.
188      *
189      * @return request
190      */
191     protected VfcRequest constructVfcRequest() {
192         ControlLoopEventContext context = params.getContext();
193         String serviceInstance = context.getEnrichment().get("service-instance.service-instance-id");
194         String vmId = context.getEnrichment().get("vserver.vserver-id");
195         String vmName = context.getEnrichment().get("vserver.vserver-name");
196
197         if (StringUtils.isBlank(serviceInstance) || StringUtils.isBlank(vmId) || StringUtils.isBlank(vmName)) {
198             throw new IllegalArgumentException(
199                     "Cannot extract enrichment data for service instance, server id, or server name.");
200         }
201
202         VfcHealActionVmInfo vmActionInfo = new VfcHealActionVmInfo();
203         vmActionInfo.setVmid(vmId);
204         vmActionInfo.setVmname(vmName);
205
206         VfcHealAdditionalParams additionalParams = new VfcHealAdditionalParams();
207         additionalParams.setAction(getName());
208         additionalParams.setActionInfo(vmActionInfo);
209
210         VfcHealRequest healRequest = new VfcHealRequest();
211         healRequest.setVnfInstanceId(params.getContext().getEvent().getAai().get(GENERIC_VNF_ID));
212         healRequest.setCause(getName());
213         healRequest.setAdditionalParams(additionalParams);
214
215         VfcRequest request = new VfcRequest();
216         request.setHealRequest(healRequest);
217         request.setNsInstanceId(serviceInstance);
218         request.setRequestId(context.getEvent().getRequestId());
219
220         return request;
221     }
222
223     // These may be overridden by jUnit tests
224
225     /**
226      * Gets the wait time, in milliseconds, between "get" requests.
227      *
228      * @return the wait time, in milliseconds, between "get" requests
229      */
230     public long getWaitMsGet() {
231         return TimeUnit.MILLISECONDS.convert(getWaitSecGet(), TimeUnit.SECONDS);
232     }
233
234     public int getMaxGets() {
235         return config.getMaxGets();
236     }
237
238     public String getPathGet() {
239         return config.getPathGet();
240     }
241
242     public int getWaitSecGet() {
243         return config.getWaitSecGet();
244     }
245 }