2  * ============LICENSE_START=======================================================
 
   3  * AppcLcmActorServiceProvider
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
 
   6  * Modifications copyright (c) 2018 Nokia
 
   7  * Modifications Copyright (C) 2019 Nordix Foundation.
 
   8  * ================================================================================
 
   9  * Licensed under the Apache License, Version 2.0 (the "License");
 
  10  * you may not use this file except in compliance with the License.
 
  11  * You may obtain a copy of the License at
 
  13  *      http://www.apache.org/licenses/LICENSE-2.0
 
  15  * Unless required by applicable law or agreed to in writing, software
 
  16  * distributed under the License is distributed on an "AS IS" BASIS,
 
  17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  18  * See the License for the specific language governing permissions and
 
  19  * limitations under the License.
 
  20  * ============LICENSE_END=========================================================
 
  23 package org.onap.policy.controlloop.actor.appclcm;
 
  25 import com.google.common.collect.ImmutableList;
 
  26 import com.google.common.collect.ImmutableMap;
 
  27 import java.util.AbstractMap;
 
  28 import java.util.AbstractMap.SimpleEntry;
 
  29 import java.util.Collections;
 
  30 import java.util.HashMap;
 
  31 import java.util.List;
 
  33 import org.onap.policy.appclcm.AppcLcmBody;
 
  34 import org.onap.policy.appclcm.AppcLcmCommonHeader;
 
  35 import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
 
  36 import org.onap.policy.appclcm.AppcLcmInput;
 
  37 import org.onap.policy.appclcm.AppcLcmOutput;
 
  38 import org.onap.policy.appclcm.AppcLcmResponseCode;
 
  39 import org.onap.policy.controlloop.ControlLoopOperation;
 
  40 import org.onap.policy.controlloop.VirtualControlLoopEvent;
 
  41 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
 
  42 import org.onap.policy.controlloop.policy.Policy;
 
  43 import org.onap.policy.controlloop.policy.PolicyResult;
 
  44 import org.slf4j.Logger;
 
  45 import org.slf4j.LoggerFactory;
 
  47 public class AppcLcmActorServiceProvider implements Actor {
 
  49     private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class);
 
  51     /* To be used in future releases to restart a single vm */
 
  52     private static final String APPC_VM_ID = "vm-id";
 
  54     // Strings for targets
 
  55     private static final String TARGET_VM = "VM";
 
  56     private static final String TARGET_VNF = "VNF";
 
  58     // Strings for recipes
 
  59     private static final String RECIPE_RESTART = "Restart";
 
  60     private static final String RECIPE_REBUILD = "Rebuild";
 
  61     private static final String RECIPE_MIGRATE = "Migrate";
 
  62     private static final String RECIPE_MODIFY = "ConfigModify";
 
  64     /* To be used in future releases when LCM ConfigModify is used */
 
  65     private static final String APPC_REQUEST_PARAMS = "request-parameters";
 
  66     private static final String APPC_CONFIG_PARAMS = "configuration-parameters";
 
  68     private static final ImmutableList<String> recipes =
 
  69             ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY);
 
  70     private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
 
  71             .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).put(RECIPE_REBUILD, ImmutableList.of(TARGET_VM))
 
  72             .put(RECIPE_MIGRATE, ImmutableList.of(TARGET_VM)).put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build();
 
  73     private static final ImmutableMap<String, List<String>> payloads =
 
  74             new ImmutableMap.Builder<String, List<String>>().put(RECIPE_RESTART, ImmutableList.of(APPC_VM_ID))
 
  75                     .put(RECIPE_MODIFY, ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build();
 
  78     public String actor() {
 
  83     public List<String> recipes() {
 
  84         return ImmutableList.copyOf(recipes);
 
  88     public List<String> recipeTargets(String recipe) {
 
  89         return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
 
  93     public List<String> recipePayloads(String recipe) {
 
  94         return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
 
  99      * Constructs an APPC request conforming to the lcm API. The actual request is constructed and
 
 100      * then placed in a wrapper object used to send through DMAAP.
 
 102      * @param onset the event that is reporting the alert for policy to perform an action
 
 103      * @param operation the control loop operation specifying the actor, operation, target, etc.
 
 104      * @param policy the policy the was specified from the yaml generated by CLAMP or through the
 
 106      * @return an APPC request conforming to the lcm API using the DMAAP wrapper
 
 108     public static AppcLcmDmaapWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
 
 109             Policy policy, String targetVnf) {
 
 111         /* Construct an APPC request using LCM Model */
 
 114          * The actual LCM request is placed in a wrapper used to send through dmaap. The current
 
 115          * version is 2.0 as of R1.
 
 117         AppcLcmRecipeFormatter lcmRecipeFormatter = new AppcLcmRecipeFormatter(policy.getRecipe());
 
 119         AppcLcmDmaapWrapper dmaapRequest = new AppcLcmDmaapWrapper();
 
 120         dmaapRequest.setVersion("2.0");
 
 121         dmaapRequest.setCorrelationId(onset.getRequestId() + "-" + operation.getSubRequestId());
 
 122         dmaapRequest.setRpcName(lcmRecipeFormatter.getUrlRecipe());
 
 123         dmaapRequest.setType("request");
 
 125         /* This is the actual request that is placed in the dmaap wrapper. */
 
 126         final AppcLcmInput appcRequest = new AppcLcmInput();
 
 128         /* The common header is a required field for all APPC requests. */
 
 129         AppcLcmCommonHeader requestCommonHeader = new AppcLcmCommonHeader();
 
 130         requestCommonHeader.setOriginatorId(onset.getRequestId().toString());
 
 131         requestCommonHeader.setRequestId(onset.getRequestId());
 
 132         requestCommonHeader.setSubRequestId(operation.getSubRequestId());
 
 134         appcRequest.setCommonHeader(requestCommonHeader);
 
 137          * Action Identifiers are required for APPC LCM requests. For R1, the recipes supported by
 
 138          * Policy only require a vnf-id.
 
 140         HashMap<String, String> requestActionIdentifiers = new HashMap<>();
 
 141         requestActionIdentifiers.put("vnf-id", targetVnf);
 
 143         appcRequest.setActionIdentifiers(requestActionIdentifiers);
 
 146          * An action is required for all APPC requests, this will be the recipe specified in the
 
 149         appcRequest.setAction(lcmRecipeFormatter.getBodyRecipe());
 
 152          * For R1, the payloads will not be required for the Restart, Rebuild, or Migrate recipes.
 
 153          * APPC will populate the payload based on A&AI look up of the vnd-id provided in the action
 
 156         if (recipeSupportsPayload(policy.getRecipe()) && payloadSupplied(policy.getPayload())) {
 
 157             appcRequest.setPayload(parsePayload(policy.getPayload()));
 
 159             appcRequest.setPayload(null);
 
 163          * The APPC request must be wrapped in an input object.
 
 165         AppcLcmBody body = new AppcLcmBody();
 
 166         body.setInput(appcRequest);
 
 169          * Once the LCM request is constructed, add it into the body of the dmaap wrapper.
 
 171         dmaapRequest.setBody(body);
 
 173         /* Return the request to be sent through dmaap. */
 
 177     private static boolean payloadSupplied(Map<String, String> payload) {
 
 178         return payload != null && !payload.isEmpty();
 
 181     private static boolean recipeSupportsPayload(String recipe) {
 
 182         return !RECIPE_RESTART.equalsIgnoreCase(recipe) && !RECIPE_REBUILD.equalsIgnoreCase(recipe)
 
 183                 && !RECIPE_MIGRATE.equalsIgnoreCase(recipe);
 
 186     private static String parsePayload(Map<String, String> payload) {
 
 187         StringBuilder payloadString = new StringBuilder("{");
 
 189             .forEach((key, value) -> payloadString.append("\"").append(key).append("\": ").append(value).append(","));
 
 190         return payloadString.substring(0, payloadString.length() - 1) + "}";
 
 194      * Parses the operation attempt using the subRequestId of APPC response.
 
 196      * @param subRequestId the sub id used to send to APPC, Policy sets this using the operation
 
 199      * @return the current operation attempt
 
 201     public static Integer parseOperationAttempt(String subRequestId) {
 
 202         Integer operationAttempt;
 
 204             operationAttempt = Integer.parseInt(subRequestId);
 
 205         } catch (NumberFormatException e) {
 
 206             logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
 
 209         return operationAttempt;
 
 213      * Processes the APPC LCM response sent from APPC. Determines if the APPC operation was
 
 214      * successful/unsuccessful and maps this to the corresponding Policy result.
 
 216      * @param dmaapResponse the dmaap wrapper message that contains the actual APPC reponse inside
 
 219      * @return an key-value pair that contains the Policy result and APPC response message
 
 221     public static SimpleEntry<PolicyResult, String> processResponse(AppcLcmDmaapWrapper dmaapResponse) {
 
 222         AppcLcmBody appcBody = dmaapResponse.getBody();
 
 223         if (appcBody == null) {
 
 224             throw new NullPointerException("APPC Body is null");
 
 227         /* The actual APPC response is inside the dmaap wrapper's body.input field. */
 
 228         AppcLcmOutput appcResponse = appcBody.getOutput();
 
 229         if (appcResponse == null) {
 
 230             throw new NullPointerException("APPC Response is null");
 
 233         /* The message returned in the APPC response. */
 
 236         /* The Policy result determined from the APPC Response. */
 
 239         /* If there is no status, Policy cannot determine if the request was successful. */
 
 240         if (appcResponse.getStatus() == null) {
 
 241             message = "Policy was unable to parse APP-C response status field (it was null).";
 
 242             return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
 
 245         /* If there is no code, Policy cannot determine if the request was successful. */
 
 246         String responseValue = AppcLcmResponseCode.toResponseValue(appcResponse.getStatus().getCode());
 
 247         if (responseValue == null) {
 
 248             message = "Policy was unable to parse APP-C response status code field.";
 
 249             return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
 
 252         /* Save the APPC response's message for Policy notification message. */
 
 253         message = appcResponse.getStatus().getMessage();
 
 255         /* Maps the APPC response result to a Policy result. */
 
 256         switch (responseValue) {
 
 257             case AppcLcmResponseCode.ACCEPTED:
 
 258                 /* Nothing to do if code is accept, continue processing */
 
 261             case AppcLcmResponseCode.SUCCESS:
 
 262                 result = PolicyResult.SUCCESS;
 
 264             case AppcLcmResponseCode.FAILURE:
 
 265                 result = PolicyResult.FAILURE;
 
 267             case AppcLcmResponseCode.REJECT:
 
 268             case AppcLcmResponseCode.ERROR:
 
 270                 result = PolicyResult.FAILURE_EXCEPTION;
 
 272         return new AbstractMap.SimpleEntry<>(result, message);