Java 17 Upgrade
[policy/models.git] / models-interactions / model-actors / actor.vfc / src / main / java / org / onap / policy / controlloop / actor / vfc / VfcOperation.java
index 573ee26..a1d4960 100644 (file)
@@ -2,7 +2,8 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2023 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 
 package org.onap.policy.controlloop.actor.vfc;
 
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.function.Function;
-import javax.ws.rs.core.Response;
-import lombok.Getter;
+import jakarta.ws.rs.core.Response;
+import java.util.List;
 import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
-import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
-import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
+import org.onap.policy.controlloop.actorserviceprovider.OperationProperties;
+import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
-import org.onap.policy.controlloop.policy.PolicyResult;
 import org.onap.policy.vfc.VfcHealActionVmInfo;
 import org.onap.policy.vfc.VfcHealAdditionalParams;
 import org.onap.policy.vfc.VfcHealRequest;
 import org.onap.policy.vfc.VfcRequest;
 import org.onap.policy.vfc.VfcResponse;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 public abstract class VfcOperation extends HttpOperation<VfcResponse> {
-    private static final Logger logger = LoggerFactory.getLogger(VfcOperation.class);
-
     public static final String FAILED = "FAILED";
     public static final String COMPLETE = "COMPLETE";
     public static final int VFC_RESPONSE_CODE = 999;
@@ -53,13 +45,19 @@ public abstract class VfcOperation extends HttpOperation<VfcResponse> {
     public static final String REQ_PARAM_NM = "requestParameters";
     public static final String CONFIG_PARAM_NM = "configurationParameters";
 
-    private final VfcConfig config;
+    // @formatter:off
+    private static final List<String> PROPERTY_NAMES = List.of(
+                            OperationProperties.ENRICHMENT_SERVICE_ID,
+                            OperationProperties.ENRICHMENT_VSERVER_ID,
+                            OperationProperties.ENRICHMENT_VSERVER_NAME,
+                            OperationProperties.ENRICHMENT_GENERIC_VNF_ID);
+    // @formatter:on
 
     /**
-     * Number of "get" requests issued so far, on the current operation attempt.
+     * Job ID extracted from the first response.
      */
-    @Getter
-    private int getCount;
+    private String jobId;
+
 
     /**
      * Constructs the object.
@@ -67,84 +65,55 @@ public abstract class VfcOperation extends HttpOperation<VfcResponse> {
      * @param params operation parameters
      * @param config configuration for this operation
      */
-    public VfcOperation(ControlLoopOperationParams params, HttpConfig config) {
-        super(params, config, VfcResponse.class);
-        this.config = (VfcConfig) config;
+    protected VfcOperation(ControlLoopOperationParams params, HttpConfig config) {
+        super(params, config, VfcResponse.class, PROPERTY_NAMES);
+
+        setUsePolling();
     }
 
-    /**
-     * Subclasses should invoke this before issuing their first HTTP request.
-     */
-    protected void resetGetCount() {
-        getCount = 0;
+    @Override
+    protected void resetPollCount() {
+        super.resetPollCount();
+        jobId = null;
     }
 
-    /**
-     * Starts the GUARD.
-     */
     @Override
-    protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
-        return startGuardAsync();
+    protected String getPollingPath() {
+        return super.getPollingPath() + jobId;
     }
 
-    /**
-     * If the response does not indicate that the request has been completed, then sleep a
-     * bit and issue a "get".
-     */
     @Override
-    protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
-            Response rawResponse, VfcResponse response) {
-        // Determine if the request has "completed" and determine if it was successful
+    protected Status detmStatus(Response rawResponse, VfcResponse response) {
         if (rawResponse.getStatus() == 200) {
             String requestState = getRequestState(response);
             if ("finished".equalsIgnoreCase(requestState)) {
-                return CompletableFuture
-                        .completedFuture(setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response));
+                extractJobId(response);
+                return Status.SUCCESS;
             }
 
             if ("error".equalsIgnoreCase(requestState)) {
-                return CompletableFuture
-                        .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
+                extractJobId(response);
+                return Status.FAILURE;
             }
         }
 
         // still incomplete
 
-        // need a request ID with which to query
-        if (response == null || response.getJobId() == null) {
+        // need a job ID with which to query
+        if (jobId == null && !extractJobId(response)) {
             throw new IllegalArgumentException("missing job ID in response");
         }
 
-        // see if the limit for the number of "gets" has been reached
-        if (getCount++ >= getMaxGets()) {
-            logger.warn("{}: execeeded 'get' limit {} for {}", getFullName(), getMaxGets(), params.getRequestId());
-            setOutcome(outcome, PolicyResult.FAILURE_TIMEOUT);
-            outcome.setResponse(response);
-            outcome.setMessage(VFC_RESPONSE_CODE + " " + outcome.getMessage());
-            return CompletableFuture.completedFuture(outcome);
-        }
-
-        // sleep and then perform a "get" operation
-        Function<Void, CompletableFuture<OperationOutcome>> doGet = unused -> issueGet(outcome, response);
-        return sleep(getWaitMsGet(), TimeUnit.MILLISECONDS).thenComposeAsync(doGet);
+        return Status.STILL_WAITING;
     }
 
-    /**
-     * Issues a "get" request to see if the original request is complete yet.
-     *
-     * @param outcome outcome to be populated with the response
-     * @param response previous response
-     * @return a future that can be used to cancel the "get" request or await its response
-     */
-    private CompletableFuture<OperationOutcome> issueGet(OperationOutcome outcome, VfcResponse response) {
-        String path = getPathGet() + response.getJobId();
-        String url = getClient().getBaseUrl() + path;
-
-        logger.debug("{}: 'get' count {} for {}", getFullName(), getCount, params.getRequestId());
-
-        logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
+    private boolean extractJobId(VfcResponse response) {
+        if (response == null || response.getJobId() == null) {
+            return false;
+        }
 
-        return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
+        jobId = response.getJobId();
+        return true;
     }
 
     /**
@@ -155,7 +124,7 @@ public abstract class VfcOperation extends HttpOperation<VfcResponse> {
      */
     protected String getRequestState(VfcResponse response) {
         if (response == null || response.getResponseDescriptor() == null
-                || StringUtils.isBlank(response.getResponseDescriptor().getStatus())) {
+                        || StringUtils.isBlank(response.getResponseDescriptor().getStatus())) {
             return null;
         }
         return response.getResponseDescriptor().getStatus();
@@ -163,7 +132,7 @@ public abstract class VfcOperation extends HttpOperation<VfcResponse> {
 
     /**
      * Treats everything as a success, so we always go into
-     * {@link #postProcessResponse(OperationOutcome, String, Response, SoResponse)}.
+     * {@link #postProcessResponse (OperationOutcome, String, Response, SoResponse)}.
      */
     @Override
     protected boolean isSuccess(Response rawResponse, VfcResponse response) {
@@ -174,14 +143,16 @@ public abstract class VfcOperation extends HttpOperation<VfcResponse> {
      * Prepends the message with the http status code.
      */
     @Override
-    public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse,
-            VfcResponse response) {
+    public OperationOutcome setOutcome(OperationOutcome outcome, OperationResult result, Response rawResponse,
+                    VfcResponse response) {
 
         // set default result and message
         setOutcome(outcome, result);
 
+        int code = (result == OperationResult.FAILURE_TIMEOUT ? VFC_RESPONSE_CODE : rawResponse.getStatus());
+
         outcome.setResponse(response);
-        outcome.setMessage(rawResponse.getStatus() + " " + outcome.getMessage());
+        outcome.setMessage(code + " " + outcome.getMessage());
         return outcome;
     }
 
@@ -191,57 +162,35 @@ public abstract class VfcOperation extends HttpOperation<VfcResponse> {
      * @return request
      */
     protected VfcRequest constructVfcRequest() {
-        ControlLoopEventContext context = params.getContext();
-        String serviceInstance = context.getEnrichment().get("service-instance.service-instance-id");
-        String vmId = context.getEnrichment().get("vserver.vserver-id");
-        String vmName = context.getEnrichment().get("vserver.vserver-name");
+        final String serviceInstance = getProperty(OperationProperties.ENRICHMENT_SERVICE_ID);
+        final String vmId = getProperty(OperationProperties.ENRICHMENT_VSERVER_ID);
+        final String vmName = getProperty(OperationProperties.ENRICHMENT_VSERVER_NAME);
+        final String vnfId = getProperty(OperationProperties.ENRICHMENT_GENERIC_VNF_ID);
 
         if (StringUtils.isBlank(serviceInstance) || StringUtils.isBlank(vmId) || StringUtils.isBlank(vmName)) {
+            // original code did not check the VNF id, so we won't check it either
             throw new IllegalArgumentException(
-                    "Cannot extract enrichment data for service instance, server id, or server name.");
+                            "Missing enrichment data for service instance, server id, or server name.");
         }
 
-        VfcHealActionVmInfo vmActionInfo = new VfcHealActionVmInfo();
+        var vmActionInfo = new VfcHealActionVmInfo();
         vmActionInfo.setVmid(vmId);
         vmActionInfo.setVmname(vmName);
 
-        VfcHealAdditionalParams additionalParams = new VfcHealAdditionalParams();
+        var additionalParams = new VfcHealAdditionalParams();
         additionalParams.setAction(getName());
         additionalParams.setActionInfo(vmActionInfo);
 
-        VfcHealRequest healRequest = new VfcHealRequest();
-        healRequest.setVnfInstanceId(params.getContext().getEvent().getAai().get(GENERIC_VNF_ID));
+        var healRequest = new VfcHealRequest();
+        healRequest.setVnfInstanceId(vnfId);
         healRequest.setCause(getName());
         healRequest.setAdditionalParams(additionalParams);
 
-        VfcRequest request = new VfcRequest();
+        var request = new VfcRequest();
         request.setHealRequest(healRequest);
         request.setNsInstanceId(serviceInstance);
-        request.setRequestId(context.getEvent().getRequestId());
+        request.setRequestId(params.getRequestId());
 
         return request;
     }
-
-    // These may be overridden by jUnit tests
-
-    /**
-     * Gets the wait time, in milliseconds, between "get" requests.
-     *
-     * @return the wait time, in milliseconds, between "get" requests
-     */
-    public long getWaitMsGet() {
-        return TimeUnit.MILLISECONDS.convert(getWaitSecGet(), TimeUnit.SECONDS);
-    }
-
-    public int getMaxGets() {
-        return config.getMaxGets();
-    }
-
-    public String getPathGet() {
-        return config.getPathGet();
-    }
-
-    public int getWaitSecGet() {
-        return config.getWaitSecGet();
-    }
 }