private CommandContext createAddVmStepContext(String currentVmName) {
    CommandContext commandCtx = null;

    try {
      Map<String, String> values = new HashMap<>();
      values.put(VdcObjectType.VM.name().toLowerCase(), currentVmName);
      Step addVmStep =
          ExecutionHandler.addSubStep(
              getExecutionContext(),
              getExecutionContext().getJob().getStep(StepEnum.EXECUTING),
              StepEnum.ADD_VM_TO_POOL,
              ExecutionMessageDirector.resolveStepMessage(StepEnum.ADD_VM_TO_POOL, values));
      ExecutionContext ctx = new ExecutionContext();
      ctx.setStep(addVmStep);
      ctx.setMonitored(true);
      commandCtx = cloneContextAndDetachFromParent().withExecutionContext(ctx);
    } catch (RuntimeException e) {
      log.error(
          "Failed to create command context of adding VM '{}' to Pool '{}': {}",
          currentVmName,
          getParameters().getVmPool().getName(),
          e.getMessage());
      log.debug("Exception", e);
    }
    return commandCtx;
  }
  /**
   * Method should be called when finalizing the command. The execution step is being ended with
   * success and the finalization step is started.
   *
   * @param executionContext The context of the job
   * @return A created instance of the Finalizing step
   */
  public static Step startFinalizingStep(ExecutionContext executionContext) {
    if (executionContext == null) {
      return null;
    }
    Step step = null;

    try {
      if (executionContext.getExecutionMethod() == ExecutionMethod.AsJob) {
        Job job = executionContext.getJob();
        if (job != null) {
          Step executingStep = job.getStep(StepEnum.EXECUTING);
          Step finalizingStep =
              job.addStep(
                  StepEnum.FINALIZING,
                  ExecutionMessageDirector.getInstance().getStepMessage(StepEnum.FINALIZING));

          if (executingStep != null) {
            executingStep.markStepEnded(true);
            JobRepositoryFactory.getJobRepository()
                .updateExistingStepAndSaveNewStep(executingStep, finalizingStep);
          } else {
            JobRepositoryFactory.getJobRepository().saveStep(finalizingStep);
          }
        }
      } else if (executionContext.getExecutionMethod() == ExecutionMethod.AsStep) {
        Step parentStep = executionContext.getStep();
        if (parentStep != null) {
          Step executingStep = parentStep.getStep(StepEnum.EXECUTING);
          Step finalizingStep =
              parentStep.addStep(
                  StepEnum.FINALIZING,
                  ExecutionMessageDirector.getInstance().getStepMessage(StepEnum.FINALIZING));
          if (executingStep != null) {
            executingStep.markStepEnded(true);
            JobRepositoryFactory.getJobRepository()
                .updateExistingStepAndSaveNewStep(executingStep, finalizingStep);
          } else {
            JobRepositoryFactory.getJobRepository().saveStep(finalizingStep);
          }
        }
      }
    } catch (Exception e) {
      log.error(e);
    }
    return step;
  }
  /**
   * Creates and returns an instance of {@link Job} entity.
   *
   * @param actionType The action type the job entity represents.
   * @param command The {@code CommandBase} instance which the job entity describes.
   * @return An initialized {@code Job} instance.
   */
  public static Job createJob(VdcActionType actionType, CommandBase<?> command) {
    Job job = new Job();

    job.setId(Guid.newGuid());
    job.setActionType(actionType);
    job.setDescription(
        ExecutionMessageDirector.resolveJobMessage(actionType, command.getJobMessageProperties()));
    job.setJobSubjectEntities(getSubjectEntities(command.getPermissionCheckSubjects()));
    job.setOwnerId(command.getUserId());
    job.setStatus(JobExecutionStatus.STARTED);
    job.setStartTime(new Date());
    job.setCorrelationId(command.getCorrelationId());

    return job;
  }
 protected CommandContext createMigrateVmContext(ExecutionContext parentContext, VM vm) {
   ExecutionContext ctx = new ExecutionContext();
   try {
     Map<String, String> values = new HashMap<>();
     values.put(VdcObjectType.VM.name().toLowerCase(), vm.getName());
     values.put(VdcObjectType.VDS.name().toLowerCase(), vm.getRunOnVdsName());
     Step step =
         ExecutionHandler.addSubStep(
             getExecutionContext(),
             parentContext.getJob().getStep(StepEnum.EXECUTING),
             StepEnum.MIGRATE_VM,
             ExecutionMessageDirector.resolveStepMessage(StepEnum.MIGRATE_VM, values));
     ctx.setJob(parentContext.getJob());
     ctx.setStep(step);
     ctx.setMonitored(true);
   } catch (RuntimeException e) {
     log.error("Failed to create ExecutionContext for MigrateVmCommand", e);
   }
   return cloneContextAndDetachFromParent().withExecutionContext(ctx);
 }
  private static Step addSubStep(Step parentStep, StepEnum stepName, String description) {
    Step step = null;

    if (parentStep != null) {
      if (description == null) {
        description = ExecutionMessageDirector.getInstance().getStepMessage(stepName);
      }
      step = parentStep.addStep(stepName, description);

      try {
        JobRepositoryFactory.getJobRepository().saveStep(step);
      } catch (Exception e) {
        log.errorFormat(
            "Failed to save new step {0} for step {1}, {2}.",
            stepName.name(), parentStep.getId(), parentStep.getStepType().name(), e);
        parentStep.getSteps().remove(step);
        step = null;
      }
    }
    return step;
  }
  /**
   * Adds a {@link Step} entity by the provided context. A {@link Step} will not be created if
   * {@code ExecutionContext.isMonitored()} returns false.
   *
   * @param context The context of the execution which defines visibility and execution method.
   * @param stepName The name of the step.
   * @param description A presentation name for the step. If not provided, the presentation name is
   *     resolved by the {@code stepName}.
   * @param isExternal Indicates if the step is invoked by a plug-in
   * @return
   */
  public static Step addStep(
      ExecutionContext context, StepEnum stepName, String description, boolean isExternal) {
    if (context == null) {
      return null;
    }
    Step step = null;

    if (context.isMonitored()) {
      if (description == null) {
        description = ExecutionMessageDirector.getInstance().getStepMessage(stepName);
      }

      try {
        Job job = context.getJob();
        if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null) {
          step = job.addStep(stepName, description);
          try {
            step.setExternal(isExternal);
            JobRepositoryFactory.getJobRepository().saveStep(step);
          } catch (Exception e) {
            log.errorFormat(
                "Failed to save new step {0} for job {1}, {2}.",
                stepName.name(), job.getId(), job.getActionType().name(), e);
            job.getSteps().remove(step);
            step = null;
          }
        } else {
          Step contextStep = context.getStep();
          if (context.getExecutionMethod() == ExecutionMethod.AsStep && contextStep != null) {
            step = addSubStep(contextStep, stepName, description);
            step.setExternal(isExternal);
          }
        }
      } catch (Exception e) {
        log.error(e);
      }
    }
    return step;
  }
  /**
   * Adds a {@link Step} entity by the provided context as a child step of a given parent step. A
   * {@link Step} will not be created if {@code ExecutionContext.isMonitored()} returns false.
   *
   * @param context The context of the execution which defines visibility and execution method.
   * @param parentStep The parent step which the new step will be added as its child.
   * @param newStepName The name of the step.
   * @param description A presentation name for the step. If not provided, the presentation name is
   *     resolved by the {@code stepName}.
   * @param isExternal Indicates if the step is invoked by a plug-in
   * @return
   */
  public static Step addSubStep(
      ExecutionContext context,
      Step parentStep,
      StepEnum newStepName,
      String description,
      boolean isExternal) {
    Step step = null;

    if (context == null || parentStep == null) {
      return null;
    }

    try {
      if (context.isMonitored()) {
        if (description == null) {
          description = ExecutionMessageDirector.getInstance().getStepMessage(newStepName);
        }

        if (context.getExecutionMethod() == ExecutionMethod.AsJob) {
          if (DbFacade.getInstance().getStepDao().exists(parentStep.getId())) {
            if (parentStep.getJobId().equals(context.getJob().getId())) {
              step = parentStep.addStep(newStepName, description);
            }
          }
        } else if (context.getExecutionMethod() == ExecutionMethod.AsStep) {
          step = parentStep.addStep(newStepName, description);
        }
      }
      if (step != null) {
        step.setExternal(isExternal);
        JobRepositoryFactory.getJobRepository().saveStep(step);
      }
    } catch (Exception e) {
      log.error(e);
    }
    return step;
  }
Example #8
0
  @Override
  protected void executeCommand() {
    Guid oVirtId = getParameters().getVdsForUniqueId();
    if (oVirtId != null) {

      // if fails to remove deprecated entry, we might attempt to add new oVirt host with an
      // existing unique-id.
      if (!removeDeprecatedOvirtEntry(oVirtId)) {
        log.error(
            "Failed to remove duplicated oVirt entry with id '{}'. Abort adding oVirt Host type",
            oVirtId);
        throw new EngineException(EngineError.HOST_ALREADY_EXISTS);
      }
    }

    TransactionSupport.executeInNewTransaction(
        () -> {
          addVdsStaticToDb();
          addVdsDynamicToDb();
          addVdsStatisticsToDb();
          getCompensationContext().stateChanged();
          return null;
        });

    if (getParameters().isProvisioned()) {
      HostProviderProxy proxy = ProviderProxyFactory.getInstance().create(getHostProvider());
      proxy.provisionHost(
          getParameters().getvds(),
          getParameters().getHostGroup(),
          getParameters().getComputeResource(),
          getParameters().getHostMac(),
          getParameters().getDiscoverName(),
          getParameters().getPassword(),
          getParameters().getDiscoverIp());

      addCustomValue("HostGroupName", getParameters().getHostGroup().getName());
      auditLogDirector.log(this, AuditLogType.VDS_PROVISION);
    }

    // set vds spm id
    if (getCluster().getStoragePoolId() != null) {
      VdsActionParameters tempVar = new VdsActionParameters(getVdsIdRef());
      tempVar.setSessionId(getParameters().getSessionId());
      tempVar.setCompensationEnabled(true);
      VdcReturnValueBase addVdsSpmIdReturn =
          runInternalAction(
              VdcActionType.AddVdsSpmId,
              tempVar,
              cloneContext().withoutLock().withoutExecutionContext());
      if (!addVdsSpmIdReturn.getSucceeded()) {
        setSucceeded(false);
        getReturnValue().setFault(addVdsSpmIdReturn.getFault());
        return;
      }
    }
    TransactionSupport.executeInNewTransaction(
        () -> {
          initializeVds(true);
          alertIfPowerManagementNotConfigured(getParameters().getVdsStaticData());
          testVdsPowerManagementStatus(getParameters().getVdsStaticData());
          setSucceeded(true);
          setActionReturnValue(getVdsIdRef());

          // If the installation failed, we don't want to compensate for the failure since it will
          // remove the
          // host, but instead the host should be left in an "install failed" status.
          getCompensationContext().cleanupCompensationDataAfterSuccessfulCommand();
          return null;
        });
    // do not install vds's which added in pending mode or for provisioning (currently power
    // clients). they are installed as part of the approve process or automatically after provision
    if (Config.<Boolean>getValue(ConfigValues.InstallVds)
        && !getParameters().isPending()
        && !getParameters().isProvisioned()) {
      final InstallVdsParameters installVdsParameters =
          new InstallVdsParameters(getVdsId(), getParameters().getPassword());
      installVdsParameters.setAuthMethod(getParameters().getAuthMethod());
      installVdsParameters.setOverrideFirewall(getParameters().getOverrideFirewall());
      installVdsParameters.setActivateHost(getParameters().getActivateHost());
      installVdsParameters.setNetworkProviderId(
          getParameters().getVdsStaticData().getOpenstackNetworkProviderId());
      installVdsParameters.setNetworkMappings(getParameters().getNetworkMappings());
      installVdsParameters.setEnableSerialConsole(getParameters().getEnableSerialConsole());
      if (getParameters().getHostedEngineDeployConfiguration() != null) {
        Map<String, String> vdsDeployParams =
            hostedEngineHelper.createVdsDeployParams(
                getVdsId(), getParameters().getHostedEngineDeployConfiguration().getDeployAction());
        installVdsParameters.setHostedEngineConfiguration(vdsDeployParams);
      }
      Map<String, String> values = new HashMap<>();
      values.put(VdcObjectType.VDS.name().toLowerCase(), getParameters().getvds().getName());
      Step installStep =
          executionHandler.addSubStep(
              getExecutionContext(),
              getExecutionContext().getJob().getStep(StepEnum.EXECUTING),
              StepEnum.INSTALLING_HOST,
              ExecutionMessageDirector.resolveStepMessage(StepEnum.INSTALLING_HOST, values));
      final ExecutionContext installCtx = new ExecutionContext();
      installCtx.setJob(getExecutionContext().getJob());
      installCtx.setStep(installStep);
      installCtx.setMonitored(true);
      installCtx.setShouldEndJob(true);
      ThreadPoolUtil.execute(
          () ->
              runInternalAction(
                  VdcActionType.InstallVdsInternal,
                  installVdsParameters,
                  cloneContextAndDetachFromParent().withExecutionContext(installCtx)));
      ExecutionHandler.setAsyncJob(getExecutionContext(), true);
    }
  }