Skip to content

Commit

Permalink
Refactor the migration pages
Browse files Browse the repository at this point in the history
  • Loading branch information
WangLiNaruto committed Nov 2, 2023
1 parent 478a0db commit ade01ac
Show file tree
Hide file tree
Showing 10 changed files with 53 additions and 110 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.eclipse.xpanse.modules.models.service.view.ServiceVo;
import org.eclipse.xpanse.modules.orchestrator.deployment.DeployTask;
import org.eclipse.xpanse.modules.orchestrator.deployment.Deployment;
import org.eclipse.xpanse.modules.workflow.consts.MigrateConstants;
import org.eclipse.xpanse.modules.workflow.utils.WorkflowProcessUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
Expand Down Expand Up @@ -158,7 +159,9 @@ public Response destroy(@PathVariable("id") String id) {
log.info("Stopping managed service with id {}", id);
DeployTask deployTask = new DeployTask();
deployTask.setId(UUID.fromString(id));
Deployment deployment = this.deployService.getDestroyHandler(deployTask);
String currentLoginUserId = deployService.getCurrentLoginUserId();
Deployment deployment =
this.deployService.getDestroyHandler(deployTask, currentLoginUserId);
this.deployService.updateServiceStatus(deployTask.getId(),
ServiceDeploymentState.DESTROYING);
this.deployService.asyncDestroyService(deployment, deployTask);
Expand All @@ -181,7 +184,9 @@ public Response purge(@PathVariable("id") String id) {
log.info("Purging managed service with id {}", id);
DeployTask deployTask = new DeployTask();
deployTask.setId(UUID.fromString(id));
Deployment deployment = this.deployService.getDestroyHandler(deployTask);
String currentLoginUserId = deployService.getCurrentLoginUserId();
Deployment deployment =
this.deployService.getDestroyHandler(deployTask, currentLoginUserId);
this.deployService.purgeService(deployment, deployTask);
String successMsg = String.format("Purging task for service with ID %s has started.", id);
return Response.successResponse(Collections.singletonList(successMsg));
Expand All @@ -199,10 +204,11 @@ public Response purge(@PathVariable("id") String id) {
public UUID migrate(@Valid @RequestBody MigrateRequest migrateRequest) {
UUID newId = UUID.randomUUID();
Map<String, Object> variable = new HashMap<>();
variable.put("id", migrateRequest.getId());
variable.put("newId", newId);
variable.put("migrateRequest", migrateRequest);
workflowProcessUtils.asyncStartProcess("migrate", variable);
variable.put(MigrateConstants.ID, migrateRequest.getId());
variable.put(MigrateConstants.NEW_ID, newId);
variable.put(MigrateConstants.MIGRATE_REQUEST, migrateRequest);
variable.put(MigrateConstants.USER_ID, deployService.getCurrentLoginUserId());
workflowProcessUtils.asyncStartProcess(MigrateConstants.PROCESS_KEY, variable);
return newId;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.xpanse.modules.models.response.Response;
import org.eclipse.xpanse.modules.models.workflow.WorkFlowTask;
import org.eclipse.xpanse.modules.security.IdentityProviderManager;
import org.eclipse.xpanse.modules.workflow.consts.MigrateConstants;
Expand Down Expand Up @@ -49,18 +48,6 @@ public class WorkFlowApi {
@Resource
private IdentityProviderManager identityProviderManager;

/**
* Query process status.
*/
@Tag(name = "WorkFlow", description = "APIs to manage the WorkFlow")
@Operation(description = "Query process status by processInstanceId")
@GetMapping(value = "/workflow/state/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public Response queryWorkFlowById(@PathVariable("id") String processInstanceId) {
String workFlowState = workflowProcessUtils.getWorkFlowState(processInstanceId);
return Response.successResponse(List.of(workFlowState));
}

/**
* Query the tasks that need to be done by me.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.eclipse.xpanse.modules.database.servicetemplate.ServiceTemplateStorage;
import org.eclipse.xpanse.modules.database.utils.EntityTransUtils;
import org.eclipse.xpanse.modules.deployment.deployers.terraform.terraformboot.model.TerraformResult;
import org.eclipse.xpanse.modules.models.security.model.CurrentUserInfo;
import org.eclipse.xpanse.modules.models.service.common.enums.Csp;
import org.eclipse.xpanse.modules.models.service.deploy.DeployRequest;
import org.eclipse.xpanse.modules.models.service.deploy.DeployResource;
Expand Down Expand Up @@ -268,7 +269,7 @@ private List<DeployResourceEntity> getDeployResourceEntityList(
*
* @param deployTask the task of deploy managed service name.
*/
public Deployment getDestroyHandler(DeployTask deployTask) {
public Deployment getDestroyHandler(DeployTask deployTask, String userId) {
// Find the deployed service.
DeployServiceEntity deployServiceEntity =
deployServiceStorage.findDeployServiceById(deployTask.getId());
Expand All @@ -278,9 +279,7 @@ public Deployment getDestroyHandler(DeployTask deployTask) {
log.error(errorMsg);
throw new ServiceNotDeployedException(errorMsg);
}
Optional<String> userIdOptional = identityProviderManager.getCurrentLoginUserId();

if (!StringUtils.equals(userIdOptional.orElse(null), deployServiceEntity.getUserId())) {
if (!StringUtils.equals(userId, deployServiceEntity.getUserId())) {
throw new AccessDeniedException(
"No permissions to destroy services belonging to other users.");
}
Expand Down Expand Up @@ -548,6 +547,19 @@ public Deployment getDeployment(DeployerKind deployerKind) {
return deployment;
}

/**
* Get the id of the current login user.
*/
public String getCurrentLoginUserId() {
CurrentUserInfo currentUserInfo = identityProviderManager.getCurrentUserInfo();
if (Objects.nonNull(currentUserInfo)
&& StringUtils.isNotBlank(currentUserInfo.getUserId())) {
return currentUserInfo.getUserId();
} else {
return "defaultUserId";
}
}

private ServiceVo convertToServiceVo(DeployServiceEntity serviceEntity) {
if (Objects.nonNull(serviceEntity)) {
ServiceVo serviceVo = new ServiceVo();
Expand Down Expand Up @@ -578,14 +590,16 @@ private void maskSensitiveFields(DeployServiceEntity deployServiceEntity) {
* Deployment service.
*/
@Async("taskExecutor")
public CompletableFuture<Void> deployService(UUID newId, DeployRequest deployRequest) {
public CompletableFuture<Void> deployService(UUID newId,
String userId, DeployRequest deployRequest) {
MDC.put(TASK_ID, newId.toString());
log.info("start deploy service, service id : {}", newId);
DeployTask deployTask = new DeployTask();
deployRequest.setId(newId);
deployTask.setId(newId);
deployTask.setDeployRequest(deployRequest);
Deployment deployment = getDeployHandler(deployTask);
deployTask.getDeployRequest().setUserId(userId);
deploy(deployment, deployTask);
return CompletableFuture.completedFuture(null);
}
Expand All @@ -594,12 +608,12 @@ public CompletableFuture<Void> deployService(UUID newId, DeployRequest deployReq
* Destroy service by deployed service id.
*/
@Async("taskExecutor")
public CompletableFuture<Void> destroyService(String id) {
public CompletableFuture<Void> destroyService(String id, String userId) {
MDC.put(TASK_ID, id);
log.info("start destroy service, service id : {}", id);
DeployTask deployTask = new DeployTask();
deployTask.setId(UUID.fromString(id));
Deployment deployment = getDestroyHandler(deployTask);
Deployment deployment = getDestroyHandler(deployTask, userId);
destroy(deployment, deployTask);
return CompletableFuture.completedFuture(null);
}
Expand All @@ -622,16 +636,18 @@ public boolean isDeploySuccess(UUID id) {
/**
* Method to determine whether destroy is successful.
*/
public boolean isDestroySuccess(UUID id) {
@Async("taskExecutor")
public CompletableFuture<Boolean> isDestroySuccess(UUID id) {
ServiceDeploymentState destroyState = null;
MDC.put(TASK_ID, id.toString());
log.info(" starting to poll for status update.. , service id : {}", id);
while (destroyState == ServiceDeploymentState.DESTROYING || destroyState == null) {
destroyState = deployServiceStorage.queryRefreshDeployServiceById(id)
destroyState = deployServiceStorage.findDeployServiceById(id)
.getServiceDeploymentState();
}
log.info("destroy status updated,state:{}", destroyState);
return destroyState == ServiceDeploymentState.DESTROY_SUCCESS;
return CompletableFuture.completedFuture(
destroyState == ServiceDeploymentState.DESTROY_SUCCESS);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ void testGetDestroyHandler_DeployedServiceNotFound_ThrowsServiceNotDeployedExcep
when(deployServiceStorage.findDeployServiceById(deployTask.getId())).thenReturn(null);

assertThrows(ServiceNotDeployedException.class,
() -> deployService.getDestroyHandler(deployTask));
() -> deployService.getDestroyHandler(deployTask, userId));
}

@Test
Expand All @@ -415,11 +415,8 @@ void testGetDestroyHandler_ServiceStateIsDestroying_ThrowsInvalidServiceStateExc

when(deployServiceStorage.findDeployServiceById(deployTask.getId())).thenReturn(
deployServiceEntity);

when(identityProviderManager.getCurrentLoginUserId()).thenReturn(Optional.of(userId));

assertThrows(InvalidServiceStateException.class,
() -> deployService.getDestroyHandler(deployTask));
() -> deployService.getDestroyHandler(deployTask, userId));
}

@Test
Expand All @@ -444,10 +441,9 @@ void testGetDestroyHandler() {
deploymentBeans.put("deploymentBean", deploymentMock);

when(applicationContext.getBeansOfType(Deployment.class)).thenReturn(deploymentBeans);
when(identityProviderManager.getCurrentLoginUserId()).thenReturn(Optional.of(userId));
deployService.deploymentMap();

Deployment result = deployService.getDestroyHandler(deployTask);
Deployment result = deployService.getDestroyHandler(deployTask, userId);

// Verify the interactions and assertions
verify(deployServiceStorage).findDeployServiceById(uuid);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ public enum ServiceDeploymentState {
DESTROYING("destroying"),
DESTROY_SUCCESS("destroy successful"),
DESTROY_FAILED("destroy failed"),
MIGRATING("migrating"),
MIGRATION_SUCCESS("migration_success"),
MIGRATION_FAILED("migration_failed"),
MANUAL_CLEANUP_REQUIRED("manual cleanup required");


Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
*/
public class MigrateConstants {

public static final String PROCESS_KEY = "migrate";
public static final String ID = "id";
public static final String NEW_ID = "newId";
public static final String MIGRATE_REQUEST = "migrateRequest";
Expand All @@ -19,6 +20,7 @@ public class MigrateConstants {
public static final String DEPLOY_RETRY_NUM = "deployRetryNum";
public static final String DESTROY_RETRY_NUM = "destroyRetryNum";
public static final String IS_RETRY_TASK = "isRetryTask";
public static final String USER_ID = "userId";

public static final String ASSIGNEE = "assignee";
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ public void execute(DelegateExecution execution) {

String processInstanceId = execution.getProcessInstanceId();
Map<String, Object> variables = runtimeService.getVariables(processInstanceId);
UUID id = (UUID) variables.get(MigrateConstants.ID);
UUID newId = (UUID) variables.get(MigrateConstants.NEW_ID);
runtimeService.updateBusinessKey(processInstanceId, newId.toString());

int deployRetryNum = (int) variables.get(MigrateConstants.DEPLOY_RETRY_NUM);

runtimeService.setVariable(processInstanceId, MigrateConstants.DEPLOY_RETRY_NUM,
Expand All @@ -67,14 +67,11 @@ public void execute(DelegateExecution execution) {
(MigrateRequest) variables.get(MigrateConstants.MIGRATE_REQUEST);
DeployRequest deployRequest = new DeployRequest();
BeanUtils.copyProperties(migrateRequest, deployRequest);

CompletableFuture<Void> future = deployService.deployService(newId, deployRequest);
String userId = (String) variables.get(MigrateConstants.USER_ID);
CompletableFuture<Void> future = deployService.deployService(newId, userId, deployRequest);
future.join();
boolean deploySuccess = deployService.isDeploySuccess(newId);
if (!deploySuccess && deployRetryNum >= 1) {
UUID id = (UUID) variables.get(MigrateConstants.ID);
String userId = deployService.getDeployServiceDetails(id)
.getDeployRequest().getUserId();
runtimeService.setVariable(processInstanceId, MigrateConstants.ASSIGNEE, userId);
}
runtimeService.setVariable(processInstanceId, MigrateConstants.IS_DEPLOY_SUCCESS,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,18 +49,19 @@ public void execute(DelegateExecution execution) {
String processInstanceId = execution.getProcessInstanceId();
Map<String, Object> variables = runtimeService.getVariables(processInstanceId);
String id = variables.get(MigrateConstants.ID).toString();
String userId = (String) variables.get(MigrateConstants.USER_ID);
int destroyRetryNum = (int) variables.get(MigrateConstants.DESTROY_RETRY_NUM);
if (destroyRetryNum > 0) {
log.info("Process instance: {} retry destroy service : {},RetryNum:{}",
processInstanceId, id, destroyRetryNum);
}
runtimeService.setVariable(processInstanceId, MigrateConstants.DESTROY_RETRY_NUM,
destroyRetryNum + 1);
CompletableFuture<Void> future = deployService.destroyService(id);
CompletableFuture<Void> future = deployService.destroyService(id, userId);
future.join();
boolean destroySuccess =
CompletableFuture<Boolean> destroySuccess =
deployService.isDestroySuccess(UUID.fromString(id));
runtimeService.setVariable(processInstanceId, MigrateConstants.IS_DESTROY_SUCCESS,
destroySuccess);
destroySuccess.get());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
package org.eclipse.xpanse.modules.workflow.utils;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
Expand All @@ -16,13 +15,10 @@
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskInfo;
import org.eclipse.xpanse.modules.models.workflow.WorkFlowTask;
import org.eclipse.xpanse.modules.models.workflow.enums.MigrateState;
import org.eclipse.xpanse.modules.workflow.consts.MigrateConstants;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

Expand Down Expand Up @@ -90,34 +86,6 @@ public List<WorkFlowTask> doneTasks(String userId) {
return transHistoricTaskInstanceToWorkFlowTask(list);
}

/**
* Query process status.
*
* @param processInstanceId Process instance ID
*/
public String getWorkFlowState(String processInstanceId) {
ProcessInstance instance = runtimeService.createProcessInstanceQuery()
.processInstanceId(processInstanceId)
.singleResult();

List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery()
.processInstanceId(processInstanceId).list();
Map<String, Object> variablesMap = new HashMap<>();
for (HistoricVariableInstance variableInstance : list) {
variablesMap.put(variableInstance.getVariableName(), variableInstance.getValue());
}

if (instance == null) {
if (variablesMap.containsKey(MigrateConstants.IS_RETRY_TASK)
&& !(boolean) variablesMap.get(MigrateConstants.IS_RETRY_TASK)) {
return MigrateState.MIGRATION_FAILED.toValue();
} else {
return MigrateState.MIGRATION_SUCCESS.toValue();
}
}
return MigrateState.MIGRATING.toValue();
}

/**
* Complete tasks based on task ID and set global process variables.
*
Expand All @@ -128,7 +96,6 @@ public void completeTask(String taskId, Map<String, Object> variables) {
taskService.complete(taskId, variables);
}


private WorkFlowTask getWorkFlow(TaskInfo task) {
WorkFlowTask workFlowTask = new WorkFlowTask();
HistoricProcessInstance instance = historyService.createHistoricProcessInstanceQuery()
Expand Down

0 comments on commit ade01ac

Please sign in to comment.