Merge "More actor clean-up"
[policy/models.git] / models-interactions / model-actors / actor.so / src / main / java / org / onap / policy / controlloop / actor / so / SoOperation.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.so;
22
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.concurrent.CompletableFuture;
27 import java.util.concurrent.TimeUnit;
28 import java.util.function.Function;
29 import javax.ws.rs.core.Response;
30 import lombok.Getter;
31 import org.onap.aai.domain.yang.CloudRegion;
32 import org.onap.aai.domain.yang.GenericVnf;
33 import org.onap.aai.domain.yang.ServiceInstance;
34 import org.onap.aai.domain.yang.Tenant;
35 import org.onap.policy.aai.AaiCqResponse;
36 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
37 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
38 import org.onap.policy.common.utils.coder.Coder;
39 import org.onap.policy.common.utils.coder.CoderException;
40 import org.onap.policy.common.utils.coder.StandardCoder;
41 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
42 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
43 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
44 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
45 import org.onap.policy.controlloop.policy.PolicyResult;
46 import org.onap.policy.controlloop.policy.Target;
47 import org.onap.policy.so.SoModelInfo;
48 import org.onap.policy.so.SoRequest;
49 import org.onap.policy.so.SoRequestInfo;
50 import org.onap.policy.so.SoRequestParameters;
51 import org.onap.policy.so.SoRequestStatus;
52 import org.onap.policy.so.SoResponse;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * Superclass for SDNC Operators. Note: subclasses should invoke {@link #resetGetCount()}
58  * each time they issue an HTTP request.
59  */
60 public abstract class SoOperation extends HttpOperation<SoResponse> {
61     private static final Logger logger = LoggerFactory.getLogger(SoOperation.class);
62     private static final Coder coder = new StandardCoder();
63
64     public static final String FAILED = "FAILED";
65     public static final String COMPLETE = "COMPLETE";
66     public static final int SO_RESPONSE_CODE = 999;
67
68     // fields within the policy payload
69     public static final String REQ_PARAM_NM = "requestParameters";
70     public static final String CONFIG_PARAM_NM = "configurationParameters";
71
72     private final SoConfig config;
73
74     /**
75      * Number of "get" requests issued so far, on the current operation attempt.
76      */
77     @Getter
78     private int getCount;
79
80
81     /**
82      * Constructs the object.
83      *
84      * @param params operation parameters
85      * @param config configuration for this operation
86      */
87     public SoOperation(ControlLoopOperationParams params, HttpConfig config) {
88         super(params, config, SoResponse.class);
89         this.config = (SoConfig) config;
90     }
91
92     /**
93      * Subclasses should invoke this before issuing their first HTTP request.
94      */
95     protected void resetGetCount() {
96         getCount = 0;
97     }
98
99     /**
100      * Starts the GUARD.
101      */
102     @Override
103     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
104         return startGuardAsync();
105     }
106
107     /**
108      * If the response does not indicate that the request has been completed, then sleep a
109      * bit and issue a "get".
110      */
111     @Override
112     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
113                     Response rawResponse, SoResponse response) {
114
115         // see if the request has "completed", whether or not it was successful
116         if (rawResponse.getStatus() == 200) {
117             String requestState = getRequestState(response);
118             if (COMPLETE.equalsIgnoreCase(requestState)) {
119                 return CompletableFuture
120                                 .completedFuture(setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response));
121             }
122
123             if (FAILED.equalsIgnoreCase(requestState)) {
124                 return CompletableFuture
125                                 .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
126             }
127         }
128
129         // still incomplete
130
131         // need a request ID with which to query
132         if (response.getRequestReferences() == null || response.getRequestReferences().getRequestId() == null) {
133             throw new IllegalArgumentException("missing request ID in response");
134         }
135
136         // see if the limit for the number of "gets" has been reached
137         if (getCount++ >= getMaxGets()) {
138             logger.warn("{}: execeeded 'get' limit {} for {}", getFullName(), getMaxGets(), params.getRequestId());
139             setOutcome(outcome, PolicyResult.FAILURE_TIMEOUT);
140             outcome.setMessage(SO_RESPONSE_CODE + " " + outcome.getMessage());
141             return CompletableFuture.completedFuture(outcome);
142         }
143
144         // sleep and then perform a "get" operation
145         Function<Void, CompletableFuture<OperationOutcome>> doGet = unused -> issueGet(outcome, response);
146         return sleep(getWaitMsGet(), TimeUnit.MILLISECONDS).thenComposeAsync(doGet);
147     }
148
149     /**
150      * Issues a "get" request to see if the original request is complete yet.
151      *
152      * @param outcome outcome to be populated with the response
153      * @param response previous response
154      * @return a future that can be used to cancel the "get" request or await its response
155      */
156     private CompletableFuture<OperationOutcome> issueGet(OperationOutcome outcome, SoResponse response) {
157         String path = getPathGet() + response.getRequestReferences().getRequestId();
158         String url = getClient().getBaseUrl() + path;
159
160         logger.debug("{}: 'get' count {} for {}", getFullName(), getCount, params.getRequestId());
161
162         logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
163
164         // TODO should this use "path" or the full "url"?
165         return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
166     }
167
168     /**
169      * Gets the request state of a response.
170      *
171      * @param response response from which to get the state
172      * @return the request state of the response, or {@code null} if it does not exist
173      */
174     protected String getRequestState(SoResponse response) {
175         SoRequest request = response.getRequest();
176         if (request == null) {
177             return null;
178         }
179
180         SoRequestStatus status = request.getRequestStatus();
181         if (status == null) {
182             return null;
183         }
184
185         return status.getRequestState();
186     }
187
188     /**
189      * Treats everything as a success, so we always go into
190      * {@link #postProcessResponse(OperationOutcome, String, Response, SoResponse)}.
191      */
192     @Override
193     protected boolean isSuccess(Response rawResponse, SoResponse response) {
194         return true;
195     }
196
197     /**
198      * Prepends the message with the http status code.
199      */
200     @Override
201     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse,
202                     SoResponse response) {
203
204         // set default result and message
205         setOutcome(outcome, result);
206
207         outcome.setMessage(rawResponse.getStatus() + " " + outcome.getMessage());
208         return outcome;
209     }
210
211     protected SoModelInfo prepareSoModelInfo() {
212         Target target = params.getTarget();
213         if (target == null) {
214             throw new IllegalArgumentException("missing Target");
215         }
216
217         if (target.getModelCustomizationId() == null || target.getModelInvariantId() == null
218                         || target.getModelName() == null || target.getModelVersion() == null
219                         || target.getModelVersionId() == null) {
220             throw new IllegalArgumentException("missing VF Module model");
221         }
222
223         SoModelInfo soModelInfo = new SoModelInfo();
224         soModelInfo.setModelCustomizationId(target.getModelCustomizationId());
225         soModelInfo.setModelInvariantId(target.getModelInvariantId());
226         soModelInfo.setModelName(target.getModelName());
227         soModelInfo.setModelVersion(target.getModelVersion());
228         soModelInfo.setModelVersionId(target.getModelVersionId());
229         soModelInfo.setModelType("vfModule");
230         return soModelInfo;
231     }
232
233     /**
234      * Construct requestInfo for the SO requestDetails.
235      *
236      * @return SO request information
237      */
238     protected SoRequestInfo constructRequestInfo() {
239         SoRequestInfo soRequestInfo = new SoRequestInfo();
240         soRequestInfo.setSource("POLICY");
241         soRequestInfo.setSuppressRollback(false);
242         soRequestInfo.setRequestorId("policy");
243         return soRequestInfo;
244     }
245
246     /**
247      * Builds the request parameters from the policy payload.
248      */
249     protected SoRequestParameters buildRequestParameters() {
250         if (params.getPayload() == null) {
251             return null;
252         }
253
254         String json = params.getPayload().get(REQ_PARAM_NM);
255         if (json == null) {
256             return null;
257         }
258
259         try {
260             return coder.decode(json, SoRequestParameters.class);
261         } catch (CoderException e) {
262             throw new IllegalArgumentException("invalid payload value: " + REQ_PARAM_NM);
263         }
264     }
265
266     /**
267      * Builds the configuration parameters from the policy payload.
268      */
269     protected List<Map<String, String>> buildConfigurationParameters() {
270         if (params.getPayload() == null) {
271             return null;
272         }
273
274         String json = params.getPayload().get(CONFIG_PARAM_NM);
275         if (json == null) {
276             return null;
277         }
278
279         try {
280             @SuppressWarnings("unchecked")
281             List<Map<String, String>> result = coder.decode(json, ArrayList.class);
282             return result;
283         } catch (CoderException | RuntimeException e) {
284             throw new IllegalArgumentException("invalid payload value: " + CONFIG_PARAM_NM);
285         }
286     }
287
288     /*
289      * These methods extract data from the Custom Query and throw an
290      * IllegalArgumentException if the desired data item is not found.
291      */
292
293     protected GenericVnf getVnfItem(AaiCqResponse aaiCqResponse, SoModelInfo soModelInfo) {
294         GenericVnf vnf = aaiCqResponse.getGenericVnfByVfModuleModelInvariantId(soModelInfo.getModelInvariantId());
295         if (vnf == null) {
296             throw new IllegalArgumentException("missing generic VNF");
297         }
298
299         return vnf;
300     }
301
302     protected ServiceInstance getServiceInstance(AaiCqResponse aaiCqResponse) {
303         ServiceInstance vnfService = aaiCqResponse.getServiceInstance();
304         if (vnfService == null) {
305             throw new IllegalArgumentException("missing VNF Service Item");
306         }
307
308         return vnfService;
309     }
310
311     protected Tenant getDefaultTenant(AaiCqResponse aaiCqResponse) {
312         Tenant tenant = aaiCqResponse.getDefaultTenant();
313         if (tenant == null) {
314             throw new IllegalArgumentException("missing Tenant Item");
315         }
316
317         return tenant;
318     }
319
320     protected CloudRegion getDefaultCloudRegion(AaiCqResponse aaiCqResponse) {
321         CloudRegion cloudRegion = aaiCqResponse.getDefaultCloudRegion();
322         if (cloudRegion == null) {
323             throw new IllegalArgumentException("missing Cloud Region");
324         }
325
326         return cloudRegion;
327     }
328
329     // these may be overridden by junit tests
330
331     /**
332      * Gets the wait time, in milliseconds, between "get" requests.
333      *
334      * @return the wait time, in milliseconds, between "get" requests
335      */
336     public long getWaitMsGet() {
337         return TimeUnit.MILLISECONDS.convert(getWaitSecGet(), TimeUnit.SECONDS);
338     }
339
340     public int getMaxGets() {
341         return config.getMaxGets();
342     }
343
344     public String getPathGet() {
345         return config.getPathGet();
346     }
347
348     public int getWaitSecGet() {
349         return config.getWaitSecGet();
350     }
351 }