SO poll should not require request ID
[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.HashMap;
25 import java.util.List;
26 import java.util.Map;
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;
33 import lombok.Getter;
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;
60
61 /**
62  * Superclass for SDNC Operators. Note: subclasses should invoke {@link #resetGetCount()}
63  * each time they issue an HTTP request.
64  */
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();
68
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;
73
74     // fields within the policy payload
75     public static final String REQ_PARAM_NM = "requestParameters";
76     public static final String CONFIG_PARAM_NM = "configurationParameters";
77
78     private final SoConfig config;
79
80     // values extracted from the parameter Target
81     private final String modelCustomizationId;
82     private final String modelInvariantId;
83     private final String modelVersionId;
84
85     private final String vfCountKey;
86
87     /**
88      * Number of "get" requests issued so far, on the current operation attempt.
89      */
90     @Getter
91     private int getCount;
92
93
94     /**
95      * Constructs the object.
96      *
97      * @param params operation parameters
98      * @param config configuration for this operation
99      */
100     public SoOperation(ControlLoopOperationParams params, HttpConfig config) {
101         super(params, config, SoResponse.class);
102         this.config = (SoConfig) config;
103
104         verifyNotNull("Target information", params.getTarget());
105
106         this.modelCustomizationId = params.getTarget().getModelCustomizationId();
107         this.modelInvariantId = params.getTarget().getModelInvariantId();
108         this.modelVersionId = params.getTarget().getModelVersionId();
109
110         vfCountKey = SoConstants.VF_COUNT_PREFIX + "[" + modelCustomizationId + "][" + modelInvariantId + "]["
111                         + modelVersionId + "]";
112     }
113
114     /**
115      * Subclasses should invoke this before issuing their first HTTP request.
116      */
117     protected void resetGetCount() {
118         getCount = 0;
119         setSubRequestId(null);
120     }
121
122     /**
123      * Validates that the parameters contain the required target information to extract
124      * the VF count from the custom query.
125      */
126     protected void validateTarget() {
127         verifyNotNull("modelCustomizationId", modelCustomizationId);
128         verifyNotNull("modelInvariantId", modelInvariantId);
129         verifyNotNull("modelVersionId", modelVersionId);
130     }
131
132     private void verifyNotNull(String type, Object value) {
133         if (value == null) {
134             throw new IllegalArgumentException("missing " + type + " for guard payload");
135         }
136     }
137
138     /**
139      * Starts the GUARD.
140      */
141     @Override
142     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
143         return startGuardAsync();
144     }
145
146     /**
147      * Gets the VF Count.
148      *
149      * @return a future to cancel or await the VF Count
150      */
151     @SuppressWarnings("unchecked")
152     protected CompletableFuture<OperationOutcome> obtainVfCount() {
153         if (params.getContext().contains(vfCountKey)) {
154             // already have the VF count
155             return null;
156         }
157
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();
161
162         // run Custom Query and then extract the VF count
163         return sequence(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams), this::storeVfCount);
164     }
165
166     /**
167      * Stores the VF count.
168      *
169      * @return {@code null}
170      */
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);
175
176             params.getContext().setProperty(vfCountKey, vfcount);
177         }
178
179         return null;
180     }
181
182     protected int getVfCount() {
183         return params.getContext().getProperty(vfCountKey);
184     }
185
186     protected void setVfCount(int vfCount) {
187         params.getContext().setProperty(vfCountKey, vfCount);
188     }
189
190     /**
191      * If the response does not indicate that the request has been completed, then sleep a
192      * bit and issue a "get".
193      */
194     @Override
195     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
196                     Response rawResponse, SoResponse response) {
197
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));
206             }
207
208             if (FAILED.equalsIgnoreCase(requestState)) {
209                 extractSubRequestId(response);
210                 return CompletableFuture
211                                 .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
212             }
213         }
214
215         // still incomplete
216
217         // need a request ID with which to query
218         if (getSubRequestId() == null && !extractSubRequestId(response)) {
219             throw new IllegalArgumentException("missing request ID in response");
220         }
221
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);
228         }
229
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);
233     }
234
235     @Override
236     public void generateSubRequestId(int attempt) {
237         setSubRequestId(null);
238     }
239
240     private boolean extractSubRequestId(SoResponse response) {
241         if (response == null || response.getRequestReferences() == null
242                         || response.getRequestReferences().getRequestId() == null) {
243             return false;
244         }
245
246         setSubRequestId(response.getRequestReferences().getRequestId());
247         return true;
248     }
249
250     /**
251      * Invoked when a request completes successfully.
252      */
253     protected void successfulCompletion() {
254         // do nothing
255     }
256
257     /**
258      * Issues a "get" request to see if the original request is complete yet.
259      *
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
262      */
263     private CompletableFuture<OperationOutcome> issueGet(OperationOutcome outcome) {
264         String path = getPathGet() + getSubRequestId();
265         String url = getClient().getBaseUrl() + path;
266
267         logger.debug("{}: 'get' count {} for {}", getFullName(), getCount, params.getRequestId());
268
269         logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
270
271         return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
272     }
273
274     /**
275      * Gets the request state of a response.
276      *
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
279      */
280     protected String getRequestState(SoResponse response) {
281         SoRequest request = response.getRequest();
282         if (request == null) {
283             return null;
284         }
285
286         SoRequestStatus status = request.getRequestStatus();
287         if (status == null) {
288             return null;
289         }
290
291         return status.getRequestState();
292     }
293
294     /**
295      * Treats everything as a success, so we always go into
296      * {@link #postProcessResponse(OperationOutcome, String, Response, SoResponse)}.
297      */
298     @Override
299     protected boolean isSuccess(Response rawResponse, SoResponse response) {
300         return true;
301     }
302
303     /**
304      * Prepends the message with the http status code.
305      */
306     @Override
307     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse,
308                     SoResponse response) {
309
310         // set default result and message
311         setOutcome(outcome, result);
312
313         outcome.setMessage(rawResponse.getStatus() + " " + outcome.getMessage());
314         return outcome;
315     }
316
317     protected SoModelInfo prepareSoModelInfo() {
318         Target target = params.getTarget();
319         if (target == null) {
320             throw new IllegalArgumentException("missing Target");
321         }
322
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");
327         }
328
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");
336         return soModelInfo;
337     }
338
339     /**
340      * Construct requestInfo for the SO requestDetails.
341      *
342      * @return SO request information
343      */
344     protected SoRequestInfo constructRequestInfo() {
345         SoRequestInfo soRequestInfo = new SoRequestInfo();
346         soRequestInfo.setSource("POLICY");
347         soRequestInfo.setSuppressRollback(false);
348         soRequestInfo.setRequestorId("policy");
349         return soRequestInfo;
350     }
351
352     /**
353      * Builds the request parameters from the policy payload.
354      */
355     protected Optional<SoRequestParameters> buildRequestParameters() {
356         if (params.getPayload() == null) {
357             return Optional.empty();
358         }
359
360         Object data = params.getPayload().get(REQ_PARAM_NM);
361         if (data == null) {
362             return Optional.empty();
363         }
364
365         try {
366             return Optional.of(coder.decode(data.toString(), SoRequestParameters.class));
367         } catch (CoderException e) {
368             throw new IllegalArgumentException("invalid payload value: " + REQ_PARAM_NM);
369         }
370     }
371
372     /**
373      * Builds the configuration parameters from the policy payload.
374      */
375     protected Optional<List<Map<String, String>>> buildConfigurationParameters() {
376         if (params.getPayload() == null) {
377             return Optional.empty();
378         }
379
380         Object data = params.getPayload().get(CONFIG_PARAM_NM);
381         if (data == null) {
382             return Optional.empty();
383         }
384
385         try {
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);
391         }
392     }
393
394     /**
395      * Construct cloudConfiguration for the SO requestDetails. Overridden for custom
396      * query.
397      *
398      * @param tenantItem tenant item from A&AI named-query response
399      * @return SO cloud configuration
400      */
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;
406     }
407
408     /**
409      * Create simple HTTP headers for unauthenticated requests to SO.
410      *
411      * @return the HTTP headers
412      */
413     protected Map<String, Object> createSimpleHeaders() {
414         Map<String, Object> headers = new HashMap<>();
415         headers.put("Accept", MediaType.APPLICATION_JSON);
416         return headers;
417     }
418
419     /*
420      * These methods extract data from the Custom Query and throw an
421      * IllegalArgumentException if the desired data item is not found.
422      */
423
424     protected GenericVnf getVnfItem(AaiCqResponse aaiCqResponse, SoModelInfo soModelInfo) {
425         GenericVnf vnf = aaiCqResponse.getGenericVnfByVfModuleModelInvariantId(soModelInfo.getModelInvariantId());
426         if (vnf == null) {
427             throw new IllegalArgumentException("missing generic VNF");
428         }
429
430         return vnf;
431     }
432
433     protected ServiceInstance getServiceInstance(AaiCqResponse aaiCqResponse) {
434         ServiceInstance vnfService = aaiCqResponse.getServiceInstance();
435         if (vnfService == null) {
436             throw new IllegalArgumentException("missing VNF Service Item");
437         }
438
439         return vnfService;
440     }
441
442     protected Tenant getDefaultTenant(AaiCqResponse aaiCqResponse) {
443         Tenant tenant = aaiCqResponse.getDefaultTenant();
444         if (tenant == null) {
445             throw new IllegalArgumentException("missing Tenant Item");
446         }
447
448         return tenant;
449     }
450
451     protected CloudRegion getDefaultCloudRegion(AaiCqResponse aaiCqResponse) {
452         CloudRegion cloudRegion = aaiCqResponse.getDefaultCloudRegion();
453         if (cloudRegion == null) {
454             throw new IllegalArgumentException("missing Cloud Region");
455         }
456
457         return cloudRegion;
458     }
459
460     // these may be overridden by junit tests
461
462     /**
463      * Gets the wait time, in milliseconds, between "get" requests.
464      *
465      * @return the wait time, in milliseconds, between "get" requests
466      */
467     public long getWaitMsGet() {
468         return TimeUnit.MILLISECONDS.convert(getWaitSecGet(), TimeUnit.SECONDS);
469     }
470
471     public int getMaxGets() {
472         return config.getMaxGets();
473     }
474
475     public String getPathGet() {
476         return config.getPathGet();
477     }
478
479     public int getWaitSecGet() {
480         return config.getWaitSecGet();
481     }
482 }