Fix the deploy cl payload issue
[clamp.git] / src / main / java / org / onap / clamp / loop / LoopOperation.java
index 5b55ab0..518830a 100644 (file)
@@ -25,351 +25,218 @@ package org.onap.clamp.loop;
 
 import com.att.eelf.configuration.EELFLogger;
 import com.att.eelf.configuration.EELFManager;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonNull;
 import com.google.gson.JsonObject;
-import com.google.gson.JsonPrimitive;
 
 import java.io.IOException;
-import java.lang.reflect.Array;
-import java.util.Collection;
-import java.util.Date;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
+import java.util.Iterator;
+import java.util.Set;
 
 import org.apache.camel.Exchange;
-import org.onap.clamp.clds.client.DcaeDispatcherServices;
-import org.onap.clamp.clds.config.ClampProperties;
-import org.onap.clamp.clds.util.LoggingUtils;
-import org.onap.clamp.clds.util.ONAPLogConstants;
-import org.onap.clamp.exception.OperationException;
-import org.onap.clamp.util.HttpConnectionManager;
-import org.slf4j.event.Level;
+import org.apache.camel.Message;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
+import org.onap.clamp.policy.operational.OperationalPolicy;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
 import org.springframework.stereotype.Component;
-import org.yaml.snakeyaml.Yaml;
 
 /**
- * Closed loop operations
+ * Closed loop operations.
  */
 @Component
 public class LoopOperation {
 
     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoopOperation.class);
     protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger();
-    private final DcaeDispatcherServices dcaeDispatcherServices;
+    private static final String DCAE_LINK_FIELD = "links";
+    private static final String DCAE_STATUS_FIELD = "status";
+    private static final String DCAE_SERVICETYPE_ID = "serviceTypeId";
+    private static final String DCAE_INPUTS = "inputs";
+    private static final String DCAE_DEPLOYMENT_PREFIX = "closedLoop_";
+    private static final String DCAE_DEPLOYMENT_SUFIX = "_deploymentId";
+    private static final String DEPLOYMENT_PARA = "dcaeDeployParameters";
     private final LoopService loopService;
-    private LoggingUtils util = new LoggingUtils(logger);
 
-    @Autowired
-    private HttpServletRequest request;
+    public enum TempLoopState {
+        NOT_SUBMITTED, SUBMITTED, DEPLOYED, NOT_DEPLOYED, PROCESSING, IN_ERROR;
+    }
 
+    /**
+     * The constructor.
+     * @param loopService The loop service
+     * @param refProp The clamp properties
+     */
     @Autowired
-    public LoopOperation(LoopService loopService, DcaeDispatcherServices dcaeDispatcherServices,
-        ClampProperties refProp, HttpConnectionManager httpConnectionManager) {
+    public LoopOperation(LoopService loopService) {
         this.loopService = loopService;
-        this.dcaeDispatcherServices = dcaeDispatcherServices;
     }
 
     /**
-     * Deploy the closed loop.
+     * Get the payload used to send the deploy closed loop request.
      *
-     * @param loopName
-     *        the loop name
-     * @return the updated loop
-     * @throws Exceptions
-     *         during the operation
+     * @param loop The loop
+     * @return The payload used to send deploy closed loop request
+     * @throws IOException IOException
      */
-    public Loop deployLoop(Exchange camelExchange, String loopName) throws OperationException {
-        util.entering(request, "CldsService: Deploy model");
-        Date startTime = new Date();
-        Loop loop = loopService.getLoop(loopName);
+    public String getDeployPayload(Loop loop) throws IOException {
+        JsonObject globalProp = loop.getGlobalPropertiesJson();
+        JsonObject deploymentProp = globalProp.getAsJsonObject(DEPLOYMENT_PARA);
 
-        if (loop == null) {
-            String msg = "Deploy loop exception: Not able to find closed loop:" + loopName;
-            util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
-                ONAPLogConstants.ResponseStatus.ERROR);
-            throw new OperationException(msg);
-        }
+        String serviceTypeId = loop.getDcaeBlueprintId();
 
-        // verify the current closed loop state
-        if (loop.getLastComputedState() != LoopState.SUBMITTED) {
-            String msg = "Deploy loop exception: This closed loop is in state:" + loop.getLastComputedState()
-                + ". It could be deployed only when it is in SUBMITTED state.";
-            util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
-            throw new OperationException(msg);
+        JsonObject rootObject = new JsonObject();
+        rootObject.addProperty(DCAE_SERVICETYPE_ID, serviceTypeId);
+        if (deploymentProp != null) {
+            rootObject.add(DCAE_INPUTS, deploymentProp);
         }
+        String apiBodyString = rootObject.toString();
+        logger.info("Dcae api Body String - " + apiBodyString);
+
+        return apiBodyString;
+    }
 
+    /**
+     * Get the deployment id.
+     *
+     * @param loop The loop
+     * @return The deployment id
+     * @throws IOException IOException
+     */
+    public String getDeploymentId(Loop loop) {
         // Set the deploymentId if not present yet
         String deploymentId = "";
         // If model is already deployed then pass same deployment id
         if (loop.getDcaeDeploymentId() != null && !loop.getDcaeDeploymentId().isEmpty()) {
             deploymentId = loop.getDcaeDeploymentId();
         } else {
-            loop.setDcaeDeploymentId(deploymentId = "closedLoop_" + loopName + "_deploymentId");
+            deploymentId = DCAE_DEPLOYMENT_PREFIX + loop.getName() + DCAE_DEPLOYMENT_SUFIX;
         }
-
-        Yaml yaml = new Yaml();
-        Map<String, Object> yamlMap = yaml.load(loop.getBlueprint());
-        JsonObject bluePrint = wrapSnakeObject(yamlMap).getAsJsonObject();
-
-        loop.setDcaeDeploymentStatusUrl(
-            dcaeDispatcherServices.createNewDeployment(deploymentId, loop.getDcaeBlueprintId(), bluePrint));
-        loop.setLastComputedState(LoopState.DEPLOYED);
-        // save the updated loop
-        loopService.saveOrUpdateLoop(loop);
-
-        // audit log
-        LoggingUtils.setTimeContext(startTime, new Date());
-        auditLogger.info("Deploy model completed");
-        util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
-        return loop;
+        return deploymentId;
     }
 
     /**
-     * Un deploy closed loop.
+     * Update the loop info.
      *
-     * @param loopName
-     *        the loop name
-     * @return the updated loop
+     * @param camelExchange The camel exchange
+     * @param loop The loop
+     * @param deploymentId The deployment id
+     * @throws ParseException The parse exception
      */
-    public Loop unDeployLoop(String loopName) throws OperationException {
-        util.entering(request, "LoopOperation: Undeploy the closed loop");
-        Date startTime = new Date();
-        Loop loop = loopService.getLoop(loopName);
+    public void updateLoopInfo(Exchange camelExchange, Loop loop, String deploymentId) throws ParseException {
+        Message in = camelExchange.getIn();
+        String msg = in.getBody(String.class);
 
-        if (loop == null) {
-            String msg = "Undeploy loop exception: Not able to find closed loop:" + loopName;
-            util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
-                ONAPLogConstants.ResponseStatus.ERROR);
-            throw new OperationException(msg);
-        }
-
-        // verify the current closed loop state
-        if (loop.getLastComputedState() != LoopState.DEPLOYED) {
-            String msg = "Unploy loop exception: This closed loop is in state:" + loop.getLastComputedState()
-                + ". It could be undeployed only when it is in DEPLOYED state.";
-            util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
-            throw new OperationException(msg);
-        }
+        JSONParser parser = new JSONParser();
+        Object obj0 = parser.parse(msg);
+        JSONObject jsonObj = (JSONObject) obj0;
 
-        loop.setDcaeDeploymentStatusUrl(
-            dcaeDispatcherServices.deleteExistingDeployment(loop.getDcaeDeploymentId(), loop.getDcaeBlueprintId()));
+        JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD);
+        String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD);
 
-        // clean the deployment ID
-        loop.setDcaeDeploymentId(null);
-        loop.setLastComputedState(LoopState.SUBMITTED);
+        // use http4 instead of http, because camel http4 component is used to do the http call
+        String newStatusUrl = statusUrl.replaceAll("http:", "http4:");
 
-        // save the updated loop
+        loop.setDcaeDeploymentId(deploymentId);
+        loop.setDcaeDeploymentStatusUrl(newStatusUrl);
         loopService.saveOrUpdateLoop(loop);
-
-        // audit log
-        LoggingUtils.setTimeContext(startTime, new Date());
-        auditLogger.info("Undeploy model completed");
-        util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
-        return loop;
-    }
-
-    private JsonElement wrapSnakeObject(Object o) {
-        // NULL => JsonNull
-        if (o == null)
-            return JsonNull.INSTANCE;
-
-        // Collection => JsonArray
-        if (o instanceof Collection) {
-            JsonArray array = new JsonArray();
-            for (Object childObj : (Collection<?>) o)
-                array.add(wrapSnakeObject(childObj));
-            return array;
-        }
-
-        // Array => JsonArray
-        if (o.getClass().isArray()) {
-            JsonArray array = new JsonArray();
-
-            int length = Array.getLength(array);
-            for (int i = 0; i < length; i++)
-                array.add(wrapSnakeObject(Array.get(array, i)));
-            return array;
-        }
-
-        // Map => JsonObject
-        if (o instanceof Map) {
-            Map<?, ?> map = (Map<?, ?>) o;
-
-            JsonObject jsonObject = new JsonObject();
-            for (final Map.Entry<?, ?> entry : map.entrySet()) {
-                final String name = String.valueOf(entry.getKey());
-                final Object value = entry.getValue();
-                jsonObject.add(name, wrapSnakeObject(value));
-            }
-            return jsonObject;
-        }
-
-        // otherwise take it as a string
-        return new JsonPrimitive(String.valueOf(o));
     }
 
     /**
-     * Submit the Ms policies.
+     * Get the Closed Loop status based on the reply from Policy.
      *
-     * @param loopName
-     *        the loop name
-     * @return the updated loop
-     * @throws IOException
-     *         IO exception
-     * @throws Exceptions
-     *         during the operation
+     * @param statusCode The status code
+     * @return The state based on policy response
+     * @throws ParseException The parse exception
      */
-    public Loop submitMsPolicies(String loopName) throws OperationException, IOException {
-        util.entering(request, "LoopOperation: delete microservice policies");
-        Date startTime = new Date();
-        Loop loop = loopService.getLoop(loopName);
-
-        if (loop == null) {
-            String msg = "Submit MS policies exception: Not able to find closed loop:" + loopName;
-            util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
-                ONAPLogConstants.ResponseStatus.ERROR);
-            throw new OperationException(msg);
+    public String analysePolicyResponse(int statusCode) {
+        if (statusCode == 200) {
+            return TempLoopState.SUBMITTED.toString();
+        } else if (statusCode == 404) {
+            return TempLoopState.NOT_SUBMITTED.toString();
         }
-
-        // verify the current closed loop state
-        if (loop.getLastComputedState() != LoopState.SUBMITTED && loop.getLastComputedState() != LoopState.DESIGN) {
-            String msg = "Submit MS policies exception: This closed loop is in state:" + loop.getLastComputedState()
-                + ". It could be deleted only when it is in SUBMITTED state.";
-            util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
-            throw new OperationException(msg);
-        }
-
-        // Establish the api call to Policy to create the ms services
-        // policyOp.createMsPolicy(loop.getMicroServicePolicies());
-
-        // audit log
-        LoggingUtils.setTimeContext(startTime, new Date());
-        auditLogger.info("Deletion of MS policies completed");
-        util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
-        return loop;
+        return TempLoopState.IN_ERROR.toString();
     }
 
     /**
-     * Delete the Ms policies.
+     * Get the name of the first Operational policy.
      *
-     * @param loopName
-     *        the loop name
-     * @return the updated loop
-     * @throws IOException
-     *         IO exception
-     * @throws Exceptions
-     *         during the operation
+     * @param loop The closed loop
+     * @return The name of the first operational policy
      */
-    public Loop deleteMsPolicies(Exchange camelExchange, String loopName) throws OperationException, IOException {
-        util.entering(request, "LoopOperation: delete microservice policies");
-        Date startTime = new Date();
-        Loop loop = loopService.getLoop(loopName);
-
-        if (loop == null) {
-            String msg = "Delete MS policies exception: Not able to find closed loop:" + loopName;
-            util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
-                ONAPLogConstants.ResponseStatus.ERROR);
-            throw new OperationException(msg);
-        }
-
-        // verify the current closed loop state
-        if (loop.getLastComputedState() != LoopState.SUBMITTED) {
-            String msg = "Delete MS policies exception: This closed loop is in state:" + loop.getLastComputedState()
-                + ". It could be deleted only when it is in SUBMITTED state.";
-            util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
-            throw new OperationException(msg);
-        }
-
-        // Establish the api call to Policy to create the ms services
-        // policyOp.deleteMsPolicy(loop.getMicroServicePolicies());
-
-        // audit log
-        LoggingUtils.setTimeContext(startTime, new Date());
-        auditLogger.info("Deletion of MS policies completed");
-        util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
-        return loop;
+    public String getOperationalPolicyName(Loop loop) {
+        Set<OperationalPolicy> opSet = (Set<OperationalPolicy>)loop.getOperationalPolicies();
+        Iterator<OperationalPolicy> iterator = opSet.iterator();
+        while (iterator.hasNext()) {
+            OperationalPolicy policy = iterator.next();
+            return policy.getName();
+        }
+        return null;
     }
 
     /**
-     * Delete the operational policy.
+     * Get the Closed Loop status based on the reply from DCAE.
      *
-     * @param loopName
-     *        the loop name
-     * @return the updated loop
-     * @throws Exceptions
-     *         during the operation
+     * @param camelExchange The camel exchange
+     * @return The state based on DCAE response
+     * @throws ParseException The parse exception
      */
-    public Loop deleteOpPolicy(Exchange camelExchange, String loopName) throws OperationException {
-        util.entering(request, "LoopOperation: delete guard policy");
-        Date startTime = new Date();
-        Loop loop = loopService.getLoop(loopName);
-
-        if (loop == null) {
-            String msg = "Delete guard policy exception: Not able to find closed loop:" + loopName;
-            util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
-                ONAPLogConstants.ResponseStatus.ERROR);
-            throw new OperationException(msg);
-        }
-
-        // verify the current closed loop state
-        if (loop.getLastComputedState() != LoopState.SUBMITTED) {
-            String msg = "Delete MS policies exception: This closed loop is in state:" + loop.getLastComputedState()
-                + ". It could be deleted only when it is in SUBMITTED state.";
-            util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
-            throw new OperationException(msg);
+    public String analyseDcaeResponse(Exchange camelExchange, Integer statusCode) throws ParseException {
+        if (statusCode == null) {
+            return TempLoopState.NOT_DEPLOYED.toString();
+        }
+        if (statusCode == 200) {
+            Message in = camelExchange.getIn();
+            String msg = in.getBody(String.class);
+
+            JSONParser parser = new JSONParser();
+            Object obj0 = parser.parse(msg);
+            JSONObject jsonObj = (JSONObject) obj0;
+
+            String opType = (String) jsonObj.get("operationType");
+            String status = (String) jsonObj.get("status");
+
+            // status = processing/successded/failed
+            if (status.equals("succeeded")) {
+                if (opType.equals("install")) {
+                    return TempLoopState.DEPLOYED.toString();
+                } else if (opType.equals("uninstall")) {
+                    return TempLoopState.NOT_DEPLOYED.toString();
+                }
+            } else if (status.equals("processing")) {
+                return TempLoopState.PROCESSING.toString();
+            }
+        } else if (statusCode == 404) {
+            return TempLoopState.NOT_DEPLOYED.toString();
         }
-
-        // Establish the api call to Policy to delete operational policy
-        // client.deleteOpPolicy();
-
-        // audit log
-        LoggingUtils.setTimeContext(startTime, new Date());
-        auditLogger.info("Deletion of Guard policy completed");
-        util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
-        return loop;
+        return TempLoopState.IN_ERROR.toString();
     }
 
     /**
-     * Delete the Guard policy.
+     * Update the status of the closed loop based on the response from Policy and DCAE.
      *
-     * @param loopName
-     *        the loop name
-     * @return the updated loop
-     * @throws Exceptions
-     *         during the operation
+     * @param loop The closed loop
+     * @param policyState The state get from Policy
+     * @param dcaeState The state get from DCAE
+     * @throws ParseException The parse exception
      */
-    public Loop deleteGuardPolicy(Exchange camelExchange, String loopName) throws OperationException {
-        util.entering(request, "LoopOperation: delete operational policy");
-        Date startTime = new Date();
-        Loop loop = loopService.getLoop(loopName);
-
-        if (loop == null) {
-            String msg = "Delete operational policy exception: Not able to find closed loop:" + loopName;
-            util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO,
-                ONAPLogConstants.ResponseStatus.ERROR);
-            throw new OperationException(msg);
-        }
-
-        // verify the current closed loop state
-        if (loop.getLastComputedState() != LoopState.SUBMITTED) {
-            String msg = "Delete MS policies exception: This closed loop is in state:" + loop.getLastComputedState()
-                + ". It could be deleted only when it is in SUBMITTED state.";
-            util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR);
-            throw new OperationException(msg);
+    public LoopState updateLoopStatus(Loop loop, TempLoopState policyState, TempLoopState dcaeState) {
+        LoopState clState = LoopState.IN_ERROR;
+        if (policyState == TempLoopState.SUBMITTED) {
+            if (dcaeState == TempLoopState.DEPLOYED) {
+                clState = LoopState.DEPLOYED;
+            } else if (dcaeState == TempLoopState.PROCESSING) {
+                clState = LoopState.WAITING;
+            } else if (dcaeState == TempLoopState.NOT_DEPLOYED) {
+                clState = LoopState.SUBMITTED;
+            }
+        } else if (policyState == TempLoopState.NOT_SUBMITTED) {
+            if (dcaeState == TempLoopState.NOT_DEPLOYED) {
+                clState = LoopState.DESIGN;
+            }
         }
-
-        // Establish the api call to Policy to delete Guard policy
-        // client.deleteOpPolicy();
-
-        // audit log
-        LoggingUtils.setTimeContext(startTime, new Date());
-        auditLogger.info("Deletion of operational policy completed");
-        util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED);
-        return loop;
+        loop.setLastComputedState(clState);
+        loopService.saveOrUpdateLoop(loop);
+        return clState;
     }
+
 }