Remove Target and TargetType
[policy/models.git] / models-interactions / model-actors / actor.vfc / src / main / java / org / onap / policy / controlloop / actor / vfc / VfcOperation.java
index 827109d..0a1136d 100644 (file)
 
 package org.onap.policy.controlloop.actor.vfc;
 
+import java.util.List;
 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 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.
@@ -68,15 +66,20 @@ public abstract class VfcOperation extends HttpOperation<VfcResponse> {
      * @param config configuration for this operation
      */
     public VfcOperation(ControlLoopOperationParams params, HttpConfig config) {
-        super(params, config, VfcResponse.class);
-        this.config = (VfcConfig) 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;
+    }
+
+    @Override
+    protected String getPollingPath() {
+        return super.getPollingPath() + jobId;
     }
 
     /**
@@ -87,63 +90,38 @@ public abstract class VfcOperation extends HttpOperation<VfcResponse> {
         return startGuardAsync();
     }
 
-    /**
-     * 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.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;
     }
 
     /**
@@ -154,7 +132,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();
@@ -173,13 +151,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);
 
-        outcome.setMessage(rawResponse.getStatus() + " " + outcome.getMessage());
+        int code = (result == OperationResult.FAILURE_TIMEOUT ? VFC_RESPONSE_CODE : rawResponse.getStatus());
+
+        outcome.setResponse(response);
+        outcome.setMessage(code + " " + outcome.getMessage());
         return outcome;
     }
 
@@ -189,14 +170,16 @@ 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 = getOptProperty(OperationProperties.ENRICHMENT_SERVICE_ID,
+                        "service-instance.service-instance-id");
+        final String vmId = getOptProperty(OperationProperties.ENRICHMENT_VSERVER_ID, "vserver.vserver-id");
+        final String vmName = getOptProperty(OperationProperties.ENRICHMENT_VSERVER_NAME, "vserver.vserver-name");
+        final String vnfId = getOptProperty(OperationProperties.ENRICHMENT_GENERIC_VNF_ID, 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.");
+                            "Cannot extract enrichment data for service instance, server id, or server name.");
         }
 
         VfcHealActionVmInfo vmActionInfo = new VfcHealActionVmInfo();
@@ -208,38 +191,32 @@ public abstract class VfcOperation extends HttpOperation<VfcResponse> {
         additionalParams.setActionInfo(vmActionInfo);
 
         VfcHealRequest healRequest = new VfcHealRequest();
-        healRequest.setVnfInstanceId(params.getContext().getEvent().getAai().get(GENERIC_VNF_ID));
+        healRequest.setVnfInstanceId(vnfId);
         healRequest.setCause(getName());
         healRequest.setAdditionalParams(additionalParams);
 
         VfcRequest 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.
+     * Gets an optional property, first checking the properties, then checking the
+     * enrichment data.
      *
-     * @return the wait time, in milliseconds, between "get" requests
+     * @param propName property name
+     * @param enrichmentName property name within the enrichment data
+     * @return the property's value, or {@code null} if it is not found
      */
-    public long getWaitMsGet() {
-        return TimeUnit.MILLISECONDS.convert(getWaitSecGet(), TimeUnit.SECONDS);
-    }
-
-    public int getMaxGets() {
-        return config.getMaxGets();
-    }
-
-    public String getPathGet() {
-        return config.getPathGet();
-    }
+    protected String getOptProperty(String propName, String enrichmentName) {
+        if (containsProperty(propName)) {
+            // return the value, even if it's null
+            return getProperty(propName);
+        }
 
-    public int getWaitSecGet() {
-        return config.getWaitSecGet();
+        return params.getContext().getEnrichment().get(enrichmentName);
     }
 }