Add other APPC-LCM operations
[policy/models.git] / models-interactions / model-actors / actor.appclcm / src / main / java / org / onap / policy / controlloop / actor / appclcm / AppcLcmActorServiceProvider.java
index 21cce2f..704c44d 100644 (file)
@@ -1,8 +1,8 @@
 /*-
  * ============LICENSE_START=======================================================
- * AppcLcmActorServiceProvider
+ * ONAP
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
  * Modifications copyright (c) 2018 Nokia
  * Modifications Copyright (C) 2019 Nordix Foundation.
  * ================================================================================
@@ -30,31 +30,34 @@ import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.UUID;
-import org.onap.policy.aai.AaiManager;
-import org.onap.policy.aai.AaiNqInstanceFilters;
-import org.onap.policy.aai.AaiNqInventoryResponseItem;
-import org.onap.policy.aai.AaiNqNamedQuery;
-import org.onap.policy.aai.AaiNqQueryParameters;
-import org.onap.policy.aai.AaiNqRequest;
-import org.onap.policy.aai.AaiNqResponse;
-import org.onap.policy.aai.util.AaiException;
-import org.onap.policy.appclcm.LcmCommonHeader;
-import org.onap.policy.appclcm.LcmRequest;
-import org.onap.policy.appclcm.LcmRequestWrapper;
-import org.onap.policy.appclcm.LcmResponse;
-import org.onap.policy.appclcm.LcmResponseCode;
-import org.onap.policy.appclcm.LcmResponseWrapper;
+import java.util.Set;
+import org.onap.policy.appclcm.AppcLcmBody;
+import org.onap.policy.appclcm.AppcLcmCommonHeader;
+import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
+import org.onap.policy.appclcm.AppcLcmInput;
+import org.onap.policy.appclcm.AppcLcmOutput;
+import org.onap.policy.appclcm.AppcLcmResponseCode;
 import org.onap.policy.controlloop.ControlLoopOperation;
 import org.onap.policy.controlloop.VirtualControlLoopEvent;
-import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
+import org.onap.policy.controlloop.actor.appc.AppcOperation;
+import org.onap.policy.controlloop.actor.appc.ModifyConfigOperation;
+import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicActor;
+import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperator;
+import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicActorParams;
 import org.onap.policy.controlloop.policy.Policy;
 import org.onap.policy.controlloop.policy.PolicyResult;
-import org.onap.policy.rest.RestManager;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class AppcLcmActorServiceProvider implements Actor {
+public class AppcLcmActorServiceProvider extends BidirectionalTopicActor<BidirectionalTopicActorParams> {
+
+    /*
+     * Confirmed by Daniel, should be 'APPC'.
+     * The actor name defined in the yaml for both legacy operations and lcm operations is still “APPC”. Perhaps in a
+     * future review it would be better to distinguish them as two separate actors in the yaml but it should be okay for
+     * now.
+     */
+    private static final String NAME = "APPC";
 
     private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class);
 
@@ -66,17 +69,16 @@ public class AppcLcmActorServiceProvider implements Actor {
     private static final String TARGET_VNF = "VNF";
 
     // Strings for recipes
-    private static final String RECIPE_RESTART = "Restart";
-    private static final String RECIPE_REBUILD = "Rebuild";
-    private static final String RECIPE_MIGRATE = "Migrate";
-    private static final String RECIPE_MODIFY = "ConfigModify";
+    private static final String RECIPE_RESTART = AppcLcmConstants.OPERATION_RESTART;
+    private static final String RECIPE_REBUILD = AppcLcmConstants.OPERATION_REBUILD;
+    private static final String RECIPE_MIGRATE = AppcLcmConstants.OPERATION_MIGRATE;
+    private static final String RECIPE_MODIFY = AppcLcmConstants.OPERATION_CONFIG_MODIFY;
 
     /* To be used in future releases when LCM ConfigModify is used */
     private static final String APPC_REQUEST_PARAMS = "request-parameters";
     private static final String APPC_CONFIG_PARAMS = "configuration-parameters";
 
-    private static final ImmutableList<String> recipes =
-            ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY);
+    private static final Set<String> recipes = AppcLcmConstants.OPERATION_NAMES;
     private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
             .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).put(RECIPE_REBUILD, ImmutableList.of(TARGET_VM))
             .put(RECIPE_MIGRATE, ImmutableList.of(TARGET_VM)).put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build();
@@ -84,9 +86,34 @@ public class AppcLcmActorServiceProvider implements Actor {
             new ImmutableMap.Builder<String, List<String>>().put(RECIPE_RESTART, ImmutableList.of(APPC_VM_ID))
                     .put(RECIPE_MODIFY, ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build();
 
+    /**
+     * Constructs the object.
+     */
+    public AppcLcmActorServiceProvider() {
+        super(NAME, BidirectionalTopicActorParams.class);
+
+        // add LCM operations first as they take precedence
+        for (String opname : AppcLcmConstants.OPERATION_NAMES) {
+            addOperator(new BidirectionalTopicOperator(NAME, opname, this, AppcLcmOperation.SELECTOR_KEYS,
+                            AppcLcmOperation::new));
+        }
+
+        // add legacy operations
+        addOperator(new BidirectionalTopicOperator(NAME, ModifyConfigOperation.NAME, this, AppcOperation.SELECTOR_KEYS,
+                        ModifyConfigOperation::new));
+    }
+
+    /**
+     * This actor should take precedence.
+     */
+    @Override
+    public int getSequenceNumber() {
+        return -1;
+    }
+
     @Override
     public String actor() {
-        return "APPC";
+        return NAME;
     }
 
     @Override
@@ -104,78 +131,6 @@ public class AppcLcmActorServiceProvider implements Actor {
         return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
     }
 
-    /**
-     * This method recursively traverses the A&AI named query response to find the generic-vnf
-     * object that contains a model-invariant-id that matches the resourceId of the policy. Once
-     * this match is found the generic-vnf object's vnf-id is returned.
-     *
-     * @param items the list of items related to the vnf returned by A&AI
-     * @param resourceId the id of the target from the sdc catalog
-     *
-     * @return the vnf-id of the target vnf to act upon or null if not found
-     */
-    private static String parseAaiResponse(List<AaiNqInventoryResponseItem> items, String resourceId) {
-        String vnfId = null;
-        for (AaiNqInventoryResponseItem item : items) {
-            if ((item.getGenericVnf() != null) && (item.getGenericVnf().getModelInvariantId() != null)
-                    && (resourceId.equals(item.getGenericVnf().getModelInvariantId()))) {
-                vnfId = item.getGenericVnf().getVnfId();
-                break;
-            } else {
-                if ((item.getItems() != null) && (item.getItems().getInventoryResponseItems() != null)) {
-                    vnfId = parseAaiResponse(item.getItems().getInventoryResponseItems(), resourceId);
-                }
-            }
-        }
-        return vnfId;
-    }
-
-    /**
-     * Constructs an A&AI Named Query using a source vnf-id to determine the vnf-id of the target
-     * entity specified in the policy to act upon.
-     *
-     * @param resourceId the id of the target from the sdc catalog
-     *
-     * @param sourceVnfId the vnf id of the source entity reporting the alert
-     *
-     * @return the target entities vnf id to act upon
-     * @throws AaiException it an error occurs
-     */
-    public static String vnfNamedQuery(String resourceId, String sourceVnfId, String aaiUrl,
-            String aaiUser, String aaiPassword) throws AaiException {
-
-        // TODO: This request id should not be hard coded in future releases
-        UUID requestId = UUID.fromString("a93ac487-409c-4e8c-9e5f-334ae8f99087");
-
-        AaiNqRequest aaiRequest = new AaiNqRequest();
-        aaiRequest.setQueryParameters(new AaiNqQueryParameters());
-        aaiRequest.getQueryParameters().setNamedQuery(new AaiNqNamedQuery());
-        aaiRequest.getQueryParameters().getNamedQuery().setNamedQueryUuid(requestId);
-
-        Map<String, Map<String, String>> filter = new HashMap<>();
-        Map<String, String> filterItem = new HashMap<>();
-
-        filterItem.put("vnf-id", sourceVnfId);
-        filter.put("generic-vnf", filterItem);
-
-        aaiRequest.setInstanceFilters(new AaiNqInstanceFilters());
-        aaiRequest.getInstanceFilters().getInstanceFilter().add(filter);
-
-        AaiNqResponse aaiResponse = new AaiManager(new RestManager()).postQuery(aaiUrl,
-                aaiUser, aaiPassword, aaiRequest, requestId);
-
-        if (aaiResponse == null) {
-            throw new AaiException("The named query response was null");
-        }
-
-        String targetVnfId = parseAaiResponse(aaiResponse.getInventoryResponseItems(), resourceId);
-        if (targetVnfId == null) {
-            throw new AaiException("Target vnf-id could not be found");
-        }
-
-        return targetVnfId;
-    }
-
     /**
      * Constructs an APPC request conforming to the lcm API. The actual request is constructed and
      * then placed in a wrapper object used to send through DMAAP.
@@ -186,7 +141,7 @@ public class AppcLcmActorServiceProvider implements Actor {
      *        Policy GUI/API
      * @return an APPC request conforming to the lcm API using the DMAAP wrapper
      */
-    public static LcmRequestWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
+    public static AppcLcmDmaapWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
             Policy policy, String targetVnf) {
 
         /* Construct an APPC request using LCM Model */
@@ -197,17 +152,17 @@ public class AppcLcmActorServiceProvider implements Actor {
          */
         AppcLcmRecipeFormatter lcmRecipeFormatter = new AppcLcmRecipeFormatter(policy.getRecipe());
 
-        LcmRequestWrapper dmaapRequest = new LcmRequestWrapper();
+        AppcLcmDmaapWrapper dmaapRequest = new AppcLcmDmaapWrapper();
         dmaapRequest.setVersion("2.0");
         dmaapRequest.setCorrelationId(onset.getRequestId() + "-" + operation.getSubRequestId());
         dmaapRequest.setRpcName(lcmRecipeFormatter.getUrlRecipe());
         dmaapRequest.setType("request");
 
         /* This is the actual request that is placed in the dmaap wrapper. */
-        final LcmRequest appcRequest = new LcmRequest();
+        final AppcLcmInput appcRequest = new AppcLcmInput();
 
         /* The common header is a required field for all APPC requests. */
-        LcmCommonHeader requestCommonHeader = new LcmCommonHeader();
+        AppcLcmCommonHeader requestCommonHeader = new AppcLcmCommonHeader();
         requestCommonHeader.setOriginatorId(onset.getRequestId().toString());
         requestCommonHeader.setRequestId(onset.getRequestId());
         requestCommonHeader.setSubRequestId(operation.getSubRequestId());
@@ -240,10 +195,16 @@ public class AppcLcmActorServiceProvider implements Actor {
             appcRequest.setPayload(null);
         }
 
+        /*
+         * The APPC request must be wrapped in an input object.
+         */
+        AppcLcmBody body = new AppcLcmBody();
+        body.setInput(appcRequest);
+
         /*
          * Once the LCM request is constructed, add it into the body of the dmaap wrapper.
          */
-        dmaapRequest.setBody(appcRequest);
+        dmaapRequest.setBody(body);
 
         /* Return the request to be sent through dmaap. */
         return dmaapRequest;
@@ -260,8 +221,8 @@ public class AppcLcmActorServiceProvider implements Actor {
 
     private static String parsePayload(Map<String, String> payload) {
         StringBuilder payloadString = new StringBuilder("{");
-        payload
-            .forEach((key, value) -> payloadString.append("\"").append(key).append("\": ").append(value).append(","));
+        payload.forEach(
+            (key, value) -> payloadString.append("\"").append(key).append("\": ").append(value).append(","));
         return payloadString.substring(0, payloadString.length() - 1) + "}";
     }
 
@@ -293,9 +254,17 @@ public class AppcLcmActorServiceProvider implements Actor {
      *
      * @return an key-value pair that contains the Policy result and APPC response message
      */
-    public static SimpleEntry<PolicyResult, String> processResponse(LcmResponseWrapper dmaapResponse) {
-        /* The actual APPC response is inside the wrapper's body field. */
-        LcmResponse appcResponse = dmaapResponse.getBody();
+    public static SimpleEntry<PolicyResult, String> processResponse(AppcLcmDmaapWrapper dmaapResponse) {
+        AppcLcmBody appcBody = dmaapResponse.getBody();
+        if (appcBody == null) {
+            throw new NullPointerException("APPC Body is null");
+        }
+
+        /* The actual APPC response is inside the dmaap wrapper's body.input field. */
+        AppcLcmOutput appcResponse = appcBody.getOutput();
+        if (appcResponse == null) {
+            throw new NullPointerException("APPC Response is null");
+        }
 
         /* The message returned in the APPC response. */
         String message;
@@ -310,7 +279,7 @@ public class AppcLcmActorServiceProvider implements Actor {
         }
 
         /* If there is no code, Policy cannot determine if the request was successful. */
-        String responseValue = LcmResponseCode.toResponseValue(appcResponse.getStatus().getCode());
+        String responseValue = AppcLcmResponseCode.toResponseValue(appcResponse.getStatus().getCode());
         if (responseValue == null) {
             message = "Policy was unable to parse APP-C response status code field.";
             return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
@@ -321,18 +290,18 @@ public class AppcLcmActorServiceProvider implements Actor {
 
         /* Maps the APPC response result to a Policy result. */
         switch (responseValue) {
-            case LcmResponseCode.ACCEPTED:
+            case AppcLcmResponseCode.ACCEPTED:
                 /* Nothing to do if code is accept, continue processing */
                 result = null;
                 break;
-            case LcmResponseCode.SUCCESS:
+            case AppcLcmResponseCode.SUCCESS:
                 result = PolicyResult.SUCCESS;
                 break;
-            case LcmResponseCode.FAILURE:
+            case AppcLcmResponseCode.FAILURE:
                 result = PolicyResult.FAILURE;
                 break;
-            case LcmResponseCode.REJECT:
-            case LcmResponseCode.ERROR:
+            case AppcLcmResponseCode.REJECT:
+            case AppcLcmResponseCode.ERROR:
             default:
                 result = PolicyResult.FAILURE_EXCEPTION;
         }