/** Should be called by backend, schedules the execution as configured. */
 void initialize() {
   log.info("Start initializing " + getClass().getSimpleName());
   SchedulerUtilQuartzImpl.getInstance()
       .scheduleACronJob(
           this,
           "onTimer",
           new Class<?>[] {},
           new Object[] {},
           Config.<String>getValue(ConfigValues.AutoRecoverySchedule));
   log.info("Finished initializing " + getClass().getSimpleName());
 }
 /**
  * Handle a BackendFailureException or an exception thrown from a backend query/action and
  * re-throw as a WebApplicationException.
  *
  * <p>If the exception indicates that the referenced backend entity does not exist
  * and @notFoundAs404 is true, then throw a WebApplicationException which wraps a 404 HTTP
  * response.
  *
  * @param clz dummy explicit type parameter for use when type inference is not possible
  *     (irrelevant in any case as a value is never returned, rather an exception is always thrown)
  * @param e the exception to handle
  * @param notFoundAs404 whether to return a 404 if appropriate
  * @returns the result of the operation
  */
 protected <T> T handleError(Class<T> clz, Exception e, boolean notFoundAs404) {
   if ((e instanceof EntityNotFoundException) && (notFoundAs404)) {
     throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build());
   } else if ((e instanceof BackendFailureException)
       && (!StringHelper.isNullOrEmpty(e.getMessage()))) {
     LOG.errorFormat(localize(Messages.BACKEND_FAILED_TEMPLATE), e.getMessage(), null);
     throw new WebFaultException(null, e.getMessage(), Response.Status.BAD_REQUEST);
   } else {
     LOG.errorFormat(localize(Messages.BACKEND_FAILED_TEMPLATE), detail(e), e);
     throw new WebFaultException(e, detail(e), Response.Status.INTERNAL_SERVER_ERROR);
   }
 }
 @Override
 public void run() {
   ExternalSchedulerDiscoveryResult discoveryResult =
       ExternalSchedulerFactory.getInstance().runDiscover();
   if (discoveryResult != null) {
     updateDB(discoveryResult);
     log.info("PolicyUnits updated");
   } else {
     AuditLogableBase loggable = new AuditLogableBase();
     AuditLogDirector.log(loggable, AuditLogType.FAILED_TO_CONNECT_TO_SCHEDULER_PROXY);
     markAllExternalPoliciesAsDisabled();
     log.warn("Discovery returned empty result, disabled external policy units");
   }
 }
 public static void loadDbFacadeConfig() throws Exception {
   boolean configSucceeded = false;
   final String ENGINE_CONF_FILE = "/etc/ovirt-engine/engine.conf";
   final String ON_START_CONNECTION_TIMEOUT = "OnStartConnectionTimeout";
   final String CONNECTION_CHECK_INTERVAL = "ConnectionCheckInterval";
   final String DEFAULT_TIMEOUT_VALUE = "300000";
   final String DEFAULT_INTERVAL_VALUE = "1000";
   InputStream inputStream = null;
   try {
     String onStartConnectionTimeout = null;
     String connectionCheckInterval = null;
     Properties props = new Properties();
     if (FileUtil.fileExists(ENGINE_CONF_FILE)) {
       // File exists, load /etc/ovirt-engine/engine.conf and set values in DbFacade
       inputStream = new FileInputStream(ENGINE_CONF_FILE);
       props.load(inputStream);
       onStartConnectionTimeout = props.getProperty(ON_START_CONNECTION_TIMEOUT);
       connectionCheckInterval = props.getProperty(CONNECTION_CHECK_INTERVAL);
       if (!validNumber(onStartConnectionTimeout)) {
         onStartConnectionTimeout = DEFAULT_TIMEOUT_VALUE;
       }
       if (!validNumber(connectionCheckInterval)) {
         connectionCheckInterval = DEFAULT_INTERVAL_VALUE;
       }
     } else {
       // File does not exist - use defaults
       log.warn(
           String.format(
               "%1$s file is not found. Please check your engine installation. "
                   + "Default values will be used",
               ENGINE_CONF_FILE));
       onStartConnectionTimeout = DEFAULT_TIMEOUT_VALUE;
       connectionCheckInterval = DEFAULT_INTERVAL_VALUE;
     }
     dbFacade.setOnStartConnectionTimeout(Integer.parseInt(onStartConnectionTimeout));
     dbFacade.setConnectionCheckInterval(Integer.parseInt(connectionCheckInterval));
     configSucceeded = true;
   } catch (Exception ex) {
     log.error("Error in configuration of db facade " + ExceptionUtils.getMessage(ex));
   } finally {
     if (!configSucceeded) {
       dbFacade.setOnStartConnectionTimeout(300000);
       dbFacade.setConnectionCheckInterval(1000);
     }
     if (inputStream != null) {
       inputStream.close();
     }
   }
 }
  private SearchParameters getSearchParameters(SearchType searchType, String constraint) {
    SearchParameters searchParams = new SearchParameters(constraint, searchType);
    HashMap<String, String> matrixConstraints =
        QueryHelper.getMatrixConstraints(
            getUriInfo(), CASE_SENSITIVE_CONSTRAINT_PARAMETER, FROM_CONSTRAINT_PARAMETER);

    // preserved in sake if backward compatibility until 4.0
    HashMap<String, String> queryConstraints =
        QueryHelper.getQueryConstraints(getUriInfo(), FROM_CONSTRAINT_PARAMETER);

    if (matrixConstraints.containsKey(FROM_CONSTRAINT_PARAMETER)) {
      try {
        searchParams.setSearchFrom(
            Long.parseLong(matrixConstraints.get(FROM_CONSTRAINT_PARAMETER)));
      } catch (Exception ex) {
        LOG.error(
            "Unwrapping of '" + FROM_CONSTRAINT_PARAMETER + "' matrix search parameter failed.",
            ex);
      }
    } else if (queryConstraints.containsKey(FROM_CONSTRAINT_PARAMETER)) {
      // preserved in sake if backward compatibility until 4.0
      try {
        searchParams.setSearchFrom(Long.parseLong(queryConstraints.get(FROM_CONSTRAINT_PARAMETER)));
      } catch (Exception ex) {
        LOG.error(
            "Unwrapping of '" + FROM_CONSTRAINT_PARAMETER + "' query search parameter failed.", ex);
      }
    }
    if (matrixConstraints.containsKey(CASE_SENSITIVE_CONSTRAINT_PARAMETER)) {
      try {
        searchParams.setCaseSensitive(
            Boolean.parseBoolean(matrixConstraints.get(CASE_SENSITIVE_CONSTRAINT_PARAMETER)));
      } catch (Exception ex) {
        LOG.error(
            "Unwrapping of '" + CASE_SENSITIVE_CONSTRAINT_PARAMETER + "' search parameter failed.",
            ex);
      }
    }

    try {
      if (QueryHelper.hasMatrixParam(getUriInfo(), MAX) && getMaxResults() != NO_LIMIT) {
        searchParams.setMaxCount(getMaxResults());
      }
    } catch (MalformedNumberException ex) {
      handleError(ex, false);
    }
    return searchParams;
  }
Пример #6
0
  /**
   * Finalizes a {@code Job} execution by a given context in which the job was performed and by the
   * exit status of the step. If the {@code Job} execution continues beyond the scope of the
   * command, the {@code Job.isAsyncJob()} should be set to {@code true}. If {@code
   * ExecutionMethod.AsStep} is defined, the current active step can end the running {@code Job} by
   * setting the {@ExecutionContext.shouldEndJob()} to {@code true}.
   *
   * @param executionContext The context of the execution which defines how the job should be ended
   * @param exitStatus Indicates if the execution described by the job ended successfully or not.
   */
  public static void endJob(ExecutionContext context, boolean exitStatus) {
    if (context == null) {
      return;
    }

    Job job = context.getJob();

    try {
      if (context.isMonitored()) {
        if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null) {
          if (context.shouldEndJob() || !(job.isAsyncJob() && exitStatus)) {
            context.setCompleted(true);
            endJob(exitStatus, job);
          }
        } else {
          Step step = context.getStep();
          if (context.getExecutionMethod() == ExecutionMethod.AsStep && step != null) {
            if (context.shouldEndJob()) {
              if (job == null) {
                job = JobRepositoryFactory.getJobRepository().getJob(step.getJobId());
              }

              if (job != null) {
                context.setCompleted(true);
                endJob(exitStatus, job);
              }
            }
          }
        }
      }
    } catch (Exception e) {
      log.error(e);
    }
  }
Пример #7
0
  /**
   * Prepares the monitoring objects for the command by the default behavior:
   *
   * <ul>
   *   <li>{@link ExecutionContext} determines how the command should be monitored. By default,
   *       non-internal commands will be associated with {@code Job} to represent the command
   *       execution. Internal commands will not be monitored by default, therefore the {@code
   *       ExecutionContext} is created as non-monitored context.
   *   <li>{@link Job} is created for monitored actions
   * </ul>
   *
   * @param command The created instance of the command (can't be <code>null</code>).
   * @param actionType The action type of the command
   * @param runAsInternal Indicates if the command should be run as internal action or not
   * @param hasCorrelationId Indicates if the current command was executed under a correlation-ID
   */
  public static void prepareCommandForMonitoring(
      CommandBase<?> command, VdcActionType actionType, boolean runAsInternal) {

    ExecutionContext context = command.getExecutionContext();
    if (context == null) {
      context = new ExecutionContext();
    }

    try {
      boolean isMonitored = shouldMonitorCommand(actionType, runAsInternal);

      // A monitored job is created for monitored external flows
      if (isMonitored || context.isJobRequired()) {
        Job job = getJob(command, actionType);
        context.setExecutionMethod(ExecutionMethod.AsJob);
        context.setJob(job);
        command.setExecutionContext(context);
        command.setJobId(job.getId());
        context.setMonitored(true);
      }
    } catch (Exception e) {
      log.errorFormat(
          "Failed to prepare command of type {0} for monitoring due to error {1}",
          actionType.name(), ExceptionUtils.getMessage(e), e);
    }
  }
Пример #8
0
  /**
   * Creates {@code ExecutionContext} which defines the context for executing the finalizing step of
   * the job. If the step exists, it must be part of a job, therefore the {@code Job} entity is
   * being set as part of the context.
   *
   * @param stepId The unique identifier of the step. Must not be {@code null}.
   * @return The context for monitoring the finalizing step of the job, or {@code null} if no such
   *     step.
   */
  public static ExecutionContext createFinalizingContext(Guid stepId) {
    ExecutionContext context = null;
    try {
      Step step = JobRepositoryFactory.getJobRepository().getStep(stepId);
      if (step != null && step.getParentStepId() != null) {
        context = new ExecutionContext();
        Step executionStep =
            JobRepositoryFactory.getJobRepository().getStep(step.getParentStepId());

        // indicates if a step is monitored at Job level or as an inner step
        Guid parentStepId = executionStep.getParentStepId();
        if (parentStepId == null) {
          context.setExecutionMethod(ExecutionMethod.AsJob);
          context.setJob(JobRepositoryFactory.getJobRepository().getJobWithSteps(step.getJobId()));
        } else {
          context.setExecutionMethod(ExecutionMethod.AsStep);
          Step parentStep = JobRepositoryFactory.getJobRepository().getStep(parentStepId);
          parentStep.setSteps(
              DbFacade.getInstance().getStepDao().getStepsByParentStepId(parentStep.getId()));
          context.setStep(parentStep);
        }
        context.setMonitored(true);
      }
    } catch (Exception e) {
      log.error(e);
    }
    return context;
  }
Пример #9
0
  /**
   * Finalizes a {@code Step} execution by a given context in which the step was performed and by
   * the exit status of the step.
   *
   * @param context The context in which the {@code Step} was executed.
   * @param step The step to finalize.
   * @param exitStatus Indicates if the execution described by the step ended successfully or not.
   */
  public static void endStep(ExecutionContext context, Step step, boolean exitStatus) {
    if (context == null) {
      return;
    }
    if (context.isMonitored()) {
      Job job = context.getJob();
      try {
        if (step != null) {
          step.markStepEnded(exitStatus);
          JobRepositoryFactory.getJobRepository().updateStep(step);
        }

        if (context.getExecutionMethod() == ExecutionMethod.AsJob && job != null && !exitStatus) {
          // step failure will cause the job to be marked as failed
          context.setCompleted(true);
          job.markJobEnded(false);
          JobRepositoryFactory.getJobRepository().updateCompletedJobAndSteps(job);
        } else {
          Step parentStep = context.getStep();
          if (context.getExecutionMethod() == ExecutionMethod.AsStep && parentStep != null) {
            context.setCompleted(true);
            if (!exitStatus) {
              job.markJobEnded(false);
              JobRepositoryFactory.getJobRepository().updateCompletedJobAndSteps(job);
            }
          }
        }
      } catch (Exception e) {
        log.error(e);
      }
    }
  }
Пример #10
0
 private static void endJob(boolean exitStatus, Job job) {
   job.markJobEnded(exitStatus);
   try {
     JobRepositoryFactory.getJobRepository().updateCompletedJobAndSteps(job);
   } catch (Exception e) {
     log.errorFormat("Failed to end Job {0}, {1}", job.getId(), job.getActionType().name(), e);
   }
 }
Пример #11
0
 /**
  * Process the return value and reply back. When exceptions raises they will be logged and set a
  * return value accordingly.
  *
  * @param timeout
  * @param unit
  * @return VDSReturnValue
  * @throws TimeoutException
  */
 @Override
 public VDSReturnValue get(long timeout, TimeUnit unit) throws TimeoutException {
   try {
     status = new StatusOnlyReturnForXmlRpc(httpTask.get(timeout, unit));
     ProceedProxyReturnValue();
   } catch (TimeoutException e) {
     httpTask.cancel(true);
     setVdsNetworkError(new VDSNetworkException(new RuntimeException(e.getCause())));
     log.error("Timeout waiting for VDSM response. " + e);
     throw e;
   } catch (Exception e) {
     log.error(e);
     setVdsRuntimeError(
         e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e));
   }
   return getVDSReturnValue();
 }
Пример #12
0
 private void removeVmStatelessImages() {
   if (getSnapshotDAO().exists(getVmId(), SnapshotType.STATELESS)) {
     log.infoFormat("Deleting snapshot for stateless vm {0}", getVmId());
     runInternalAction(
         VdcActionType.RestoreStatelessVm,
         new VmOperationParameterBase(getVmId()),
         ExecutionHandler.createDefaultContextForTasks(getContext(), getLock()));
   }
 }
 private <T extends Enum<T>> String getMessage(Map<T, String> map, T type) {
   String message = map.get(type);
   if (message == null) {
     log.warnFormat(
         "The message key {0} is missing from {1}", type.name(), EXECUTION_MESSAGES_FILE_PATH);
     message = type.name();
   }
   return message;
 }
  /**
   * Adds a pair of {@code Enum} and message to the messages map. If the key is not valid, an error
   * message is logged. The key should be resolvable as an {@code Enum}, once its prefix is trimmed
   * and the searched for an {@code Enum} match by name. Possible entries of (key,value) from the
   * resource bundle:
   *
   * <pre>
   * job.ChangeVMCluster=Change VM ${VM} Cluster to ${VdsGroups}
   * step.VALIDATING=Validating
   * </pre>
   *
   * @param key The key of the pair to be added, by which the enum is searched.
   * @param value The message of the pair to be added
   * @param enumClass The enum class search for an instance which match the key
   * @param messagesMap The map whic the message should be added to
   * @param prefixLength The length of the key prefix
   */
  private <T extends Enum<T>> void addMessage(
      String key, String value, Map<T, String> messagesMap, Class<T> enumClass, int prefixLength) {

    T enumKey = null;

    try {
      enumKey = T.valueOf(enumClass, key.substring(prefixLength));
    } catch (IllegalArgumentException e) {
      log.errorFormat("Message key {0} is not valid for enum {1}", key, enumClass.getSimpleName());
      return;
    }

    if (!messagesMap.containsKey(key)) {
      messagesMap.put(enumKey, value);
    } else {
      log.warnFormat(
          "Code {0} appears more then once in {1} table.", key, enumClass.getSimpleName());
    }
  }
Пример #15
0
 static String detail(Throwable t) {
   String detail = null;
   if (LOG.isDebugEnabled()) {
     StringWriter sw = new StringWriter();
     t.printStackTrace(new PrintWriter(sw, true));
     detail = sw.toString();
   } else {
     detail = t.getMessage();
   }
   return detail;
 }
Пример #16
0
 /**
  * Updates Job for the same entity for a specific action as completed with a given exit status.
  *
  * @param entityId The entity to search for its jobs
  * @param actionType The action type to search for
  * @param status The exist status to be set for the job
  */
 public static void updateSpecificActionJobCompleted(
     Guid entityId, VdcActionType actionType, boolean status) {
   try {
     List<Job> jobs =
         JobRepositoryFactory.getJobRepository().getJobsByEntityAndAction(entityId, actionType);
     for (Job job : jobs) {
       if (job.getStatus() == JobExecutionStatus.STARTED) job.markJobEnded(status);
       JobRepositoryFactory.getJobRepository().updateCompletedJobAndSteps(job);
     }
   } catch (RuntimeException e) {
     log.error(e);
   }
 }
Пример #17
0
  /**
   * 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;
  }
Пример #18
0
 /**
  * Updates the step with the id in the external system in which the describe task runs.
  *
  * @param step The step which represents the external task
  * @param externalId The id of the task in the external system
  * @param systemType The type of the system
  */
 public static void updateStepExternalId(
     Step step, Guid externalId, ExternalSystemType systemType) {
   if (step != null) {
     step.getExternalSystem().setId(externalId);
     step.getExternalSystem().setType(systemType);
     try {
       JobRepositoryFactory.getJobRepository().updateStep(step);
     } catch (Exception e) {
       log.errorFormat(
           "Failed to save step {0}, {1} for system-type {2} with id {3}",
           step.getId(), step.getStepType().name(), systemType.name(), externalId, e);
     }
   }
 }
Пример #19
0
  /**
   * Finalizes a {@code Step} execution which represents a VDSM task. In case of a failure status,
   * the job will not be marked as failed at this stage, but via executing the {@code
   * CommandBase.endAction} with the proper status by {@code the AsyncTaskManager}.
   *
   * @param stepId A unique identifier of the step to finalize.
   * @param exitStatus The status which the step should be ended with.
   */
  public static void endTaskStep(Guid stepId, JobExecutionStatus exitStatus) {
    try {
      if (stepId != null) {
        Step step = JobRepositoryFactory.getJobRepository().getStep(stepId);

        if (step != null) {
          step.markStepEnded(exitStatus);
          JobRepositoryFactory.getJobRepository().updateStep(step);
        }
      }
    } catch (Exception e) {
      log.errorFormat("Failed to terminate step {0} with status {1}", stepId, exitStatus, e);
    }
  }
 protected void getEntity(String id) {
   try {
     Method method = getMethod(this.getClass(), SingleEntityResource.class);
     if (method == null) {
       LOG.error("Could not find sub-resource in the collection resource");
     } else {
       Object entityResource = method.invoke(this, id);
       method = entityResource.getClass().getMethod("get");
       method.invoke(entityResource);
     }
   } catch (IllegalAccessException e) {
     LOG.error("Reflection Error", e);
   } catch (InvocationTargetException e) {
     if (e.getTargetException() instanceof WebApplicationException) {
       throw ((WebApplicationException) e.getTargetException());
     } else {
       LOG.error("Reflection Error", e);
     }
   } catch (SecurityException e) {
     LOG.error("Reflection Error", e);
   } catch (NoSuchMethodException e) {
     LOG.error("Reflection Error", e);
   }
 }
 /**
  * Check all the failing resources retrieved from the dao.
  *
  * @param dao the dao to get the list of failing resources from
  * @param actionType autorecovery action
  * @param paramsCallback a closure to create the parameters for the autorecovery action
  * @param filter a filter to select the recoverable resources
  * @param logMsg a user-readable name for the failing resource type
  */
 <T extends BusinessEntity<Guid>> void check(
     final AutoRecoverDAO<T> dao,
     final VdcActionType actionType,
     final DoWithClosure<T, VdcActionParametersBase> paramsCallback,
     final FilterClosure<T> filter,
     final String logMsg) {
   if (!shouldPerformRecoveryOnType(logMsg)) {
     log.info("Autorecovering " + logMsg + " is disabled, skipping");
     return;
   }
   log.debugFormat("Checking autorecoverable {0}", logMsg);
   final List<T> fails = filter.filter(dao.listFailedAutorecoverables());
   if (fails.size() > 0) {
     final BackendInternal backend = getBackend();
     log.info("Autorecovering " + fails.size() + " " + logMsg);
     for (final T fail : fails) {
       log.info("Autorecovering " + logMsg + " id: " + fail.getId() + getHostName(fail));
       final VdcActionParametersBase actionParams = paramsCallback.doWith(fail);
       actionParams.setShouldBeLogged(true);
       backend.runInternalAction(actionType, actionParams);
     }
   }
   log.debugFormat("Checking autorecoverable {0} done", logMsg);
 }
  /**
   * This method checks if the virtual machine is running in some host. It also has the side effect
   * of storing the reference to the host inside the command.
   *
   * @return <code>true</code> if the virtual machine is running in a any host, <code>false</code>
   *     otherwise
   */
  protected boolean GetRunningOnVds() {
    // We will need the virtual machine and the status, so it is worth saving references:
    final VM vm = getVm();
    final VMStatus status = vm.getstatus();

    // If the status of the machine implies that it is not running in a host then
    // there is no need to find the id of the host:
    if (!VM.isStatusUpOrPaused(status) && status != VMStatus.NotResponding) {
      return false;
    }

    // Find the id of the host where the machine is running:
    NGuid hostId = vm.getrun_on_vds();
    if (hostId == null) {
      log.warnFormat(
          "Strange, according to the status \"{0}\" virtual machine \"{1}\" should be running in a host but it isn't.",
          status, vm.getId());
      return false;
    }

    // Find the reference to the host using the id that we got before (setting
    // the host to null is required in order to make sure that the host is
    // reloaded from the database):
    setVdsId(new Guid(hostId.toString()));
    setVds(null);
    if (getVds() == null) {
      log.warnFormat(
          "Strange, virtual machine \"{0}\" is is running in host \"{1}\" but that host can't be found.",
          vm.getId(), hostId);
      return false;
    }

    // If we are here everything went right, so the machine is running in
    // a host:
    return true;
  }
Пример #23
0
  /**
   * 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;
  }
  /**
   * Load resources files and initialize the messages cache.
   *
   * @param bundleBaseName The base name of the resource bundle
   */
  public void initialize(String bundleBaseName) {
    ResourceBundle bundle = ResourceBundle.getBundle(bundleBaseName);
    final int jobMessagePrefixLength = JOB_MESSAGE_PREFIX.length();
    final int stepMessagePrefixLength = STEP_MESSAGE_PREFIX.length();

    for (String key : bundle.keySet()) {

      if (key.startsWith(JOB_MESSAGE_PREFIX)) {
        addMessage(
            key, bundle.getString(key), jobMessages, VdcActionType.class, jobMessagePrefixLength);
      } else if (key.startsWith(STEP_MESSAGE_PREFIX)) {
        addMessage(
            key, bundle.getString(key), stepMessages, StepEnum.class, stepMessagePrefixLength);
      } else {
        log.errorFormat(
            "The message key {0} cannot be categorized since not started with {1} nor {2}",
            key, JOB_MESSAGE_PREFIX, STEP_MESSAGE_PREFIX);
      }
    }
  }
Пример #25
0
  static {
    try {
      // ok we need to locate the datasource
      DataSource datasource = EjbUtils.findResource(ContainerManagedResourceType.DATA_SOURCE);
      if (datasource == null) throw new RuntimeException("Datasource is not defined ");

      // create the facade and return it
      dbFacade = new DbFacade();
      dbFacade.setDbEngineDialect(loadDbEngineDialect());
      loadDbFacadeConfig();
      JdbcTemplate jdbcTemplate = dbFacade.getDbEngineDialect().createJdbcTemplate(datasource);
      SQLErrorCodeSQLExceptionTranslator tr =
          new CustomSQLErrorCodeSQLExceptionTranslator(datasource);
      jdbcTemplate.setExceptionTranslator(tr);

      dbFacade.setTemplate(jdbcTemplate);
    } catch (Exception e) {
      log.fatal("Unable to locate DbFacade instance", e);
    }
  }
Пример #26
0
  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;
  }
Пример #27
0
  /**
   * Finalizes Job with VDSM tasks, as this case requires verification that no other steps are
   * running in order to close the entire Job
   *
   * @param executionContext The context of the execution which defines how the job should be ended
   * @param exitStatus Indicates if the execution described by the job ended successfully or not.
   */
  public static void endTaskJob(ExecutionContext context, boolean exitStatus) {
    if (context == null) {
      return;
    }

    try {
      if (context.getExecutionMethod() == ExecutionMethod.AsJob && context.getJob() != null) {
        endJob(context, exitStatus);
      } else {
        Step parentStep = context.getStep();
        if (context.getExecutionMethod() == ExecutionMethod.AsStep && parentStep != null) {
          Step finalizingStep = parentStep.getStep(StepEnum.FINALIZING);
          if (finalizingStep != null) {
            finalizingStep.markStepEnded(exitStatus);
            JobRepositoryFactory.getJobRepository().updateStep(finalizingStep);
          }
          parentStep.markStepEnded(exitStatus);
          JobRepositoryFactory.getJobRepository().updateStep(parentStep);

          List<Step> steps =
              DbFacade.getInstance().getStepDao().getStepsByJobId(parentStep.getJobId());
          boolean hasChildStepsRunning = false;
          for (Step step : steps) {
            if (step.getStatus() == JobExecutionStatus.STARTED && step.getParentStepId() != null) {
              hasChildStepsRunning = true;
              break;
            }
          }
          if (!hasChildStepsRunning) {
            endJob(
                exitStatus, JobRepositoryFactory.getJobRepository().getJob(parentStep.getJobId()));
          }
        }
      }
    } catch (RuntimeException e) {
      log.error(e);
    }
  }
Пример #28
0
  /**
   * Checks if a Job has any Step associated with VDSM task
   *
   * @param context The context of the execution stores the Job
   * @return true if Job has any Step for VDSM Task, else false.
   */
  public static boolean checkIfJobHasTasks(ExecutionContext context) {
    if (context == null || !context.isMonitored()) {
      return false;
    }

    try {
      Guid jobId = null;
      if (context.getExecutionMethod() == ExecutionMethod.AsJob && context.getJob() != null) {
        jobId = context.getJob().getId();
      } else if (context.getExecutionMethod() == ExecutionMethod.AsStep
          && context.getStep() != null) {
        jobId = context.getStep().getId();
      }

      if (jobId != null) {
        return DbFacade.getInstance().getJobDao().checkIfJobHasTasks(jobId);
      }
    } catch (RuntimeException e) {
      log.error(e);
    }

    return false;
  }
Пример #29
0
  /**
   * 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;
  }
  /**
   * Update the given VM with the (static) data that is contained in the configuration. The {@link
   * VM#getImages()} will contain the images that were read from the configuration.
   *
   * @param vm The VM to update.
   * @param configuration The configuration to update from.
   * @return In case of a problem reading the configuration, <code>false</code>. Otherwise, <code>
   *     true</code>.
   */
  public boolean updateVmFromConfiguration(VM vm, String configuration) {

    try {
      VmStatic oldVmStatic = vm.getStaticData();
      RefObject<VM> vmRef = new RefObject<VM>();
      RefObject<ArrayList<DiskImage>> imagesRef = new RefObject<ArrayList<DiskImage>>();
      RefObject<ArrayList<VmNetworkInterface>> interfacesRef =
          new RefObject<ArrayList<VmNetworkInterface>>();
      new OvfManager().ImportVm(configuration, vmRef, imagesRef, interfacesRef);
      new VMStaticOvfLogHandler(vmRef.argvalue.getStaticData()).resetDefaults(oldVmStatic);

      vm.setStaticData(vmRef.argvalue.getStaticData());
      vm.setImages(imagesRef.argvalue);
      vm.setInterfaces(interfacesRef.argvalue);

      // These fields are not saved in the OVF, so get them from the current VM.
      vm.setdedicated_vm_for_vds(oldVmStatic.getdedicated_vm_for_vds());
      vm.setiso_path(oldVmStatic.getiso_path());
      vm.setvds_group_id(oldVmStatic.getvds_group_id());
      // The VM configuration does not hold the vds group Id.
      // It is necessary to fetch the vm static from the Db, in order to get this information
      VmStatic vmStaticFromDb = getVmStaticDao().get(vm.getId());
      if (vmStaticFromDb != null) {
        VDSGroup vdsGroup = getVdsGroupDao().get(vmStaticFromDb.getvds_group_id());
        if (vdsGroup != null) {
          vm.setvds_group_compatibility_version(vdsGroup.getcompatibility_version());
          vm.setvds_group_name(vdsGroup.getname());
          vm.setvds_group_cpu_name(vdsGroup.getcpu_name());
        }
      }
      return true;
    } catch (OvfReaderException e) {
      log.errorFormat("Failed to update VM from the configuration: {0}).", configuration, e);
      return false;
    }
  }