Ejemplo n.º 1
0
  private AsyncTaskManager(CommandCoordinator coco) {
    this.coco = coco;
    _tasks = new ConcurrentHashMap<>();

    SchedulerUtil scheduler = Injector.get(SchedulerUtilQuartzImpl.class);
    scheduler.scheduleAFixedDelayJob(
        this,
        "timerElapsed",
        new Class[] {},
        new Object[] {},
        Config.<Integer>getValue(ConfigValues.AsyncTaskPollingRate),
        Config.<Integer>getValue(ConfigValues.AsyncTaskPollingRate),
        TimeUnit.SECONDS);

    scheduler.scheduleAFixedDelayJob(
        this,
        "cacheTimerElapsed",
        new Class[] {},
        new Object[] {},
        Config.<Integer>getValue(ConfigValues.AsyncTaskStatusCacheRefreshRateInSeconds),
        Config.<Integer>getValue(ConfigValues.AsyncTaskStatusCacheRefreshRateInSeconds),
        TimeUnit.SECONDS);
    _cacheTimeInMinutes =
        Config.<Integer>getValue(ConfigValues.AsyncTaskStatusCachingTimeInMinutes);
  }
Ejemplo n.º 2
0
 @Test
 public void testGetValue() {
   // Verify that values for 3.0 and 3.2 are from DB (since the entries are present in
   // fixtures.xml)
   // and for 3.1, it's the default value from annotation in ConfigValues.
   // 3.0 -> false, 3.1 -> true, 3.2 -> true
   Assert.assertFalse(Config.<Boolean>getValue(ConfigValues.NonVmNetworkSupported, "3.0"));
   Assert.assertTrue(Config.<Boolean>getValue(ConfigValues.NonVmNetworkSupported, "3.1"));
   Assert.assertTrue(Config.<Boolean>getValue(ConfigValues.NonVmNetworkSupported, "3.2"));
 }
Ejemplo n.º 3
0
 /**
  * Determines whether [is high availability value legal] [the specified value].
  *
  * @param value The value.
  * @param reasons The reasons.
  * @return <c>true</c> if [is vm priority value legal] [the specified value]; otherwise,
  *     <c>false</c>.
  */
 public static boolean isVmPriorityValueLegal(int value, List<String> reasons) {
   boolean res = false;
   if (value >= 0 && value <= Config.<Integer>getValue(ConfigValues.VmPriorityMaxValue)) {
     res = true;
   } else {
     reasons.add(EngineMessage.VM_OR_TEMPLATE_ILLEGAL_PRIORITY_VALUE.toString());
     reasons.add(
         String.format(
             "$MaxValue %1$s", Config.<Integer>getValue(ConfigValues.VmPriorityMaxValue)));
   }
   return res;
 }
Ejemplo n.º 4
0
  private int getMaximumMigrationDowntime() {
    if (getVm().getMigrationDowntime() != null) {
      return getVm().getMigrationDowntime();
    }

    return Config.getValue(ConfigValues.DefaultMaximumMigrationDowntime);
  }
  private void addVmsToPool(Guid poolId) {
    int subsequentFailedAttempts = 0;
    int vmPoolMaxSubsequentFailures =
        Config.<Integer>getValue(ConfigValues.VmPoolMaxSubsequentFailures);

    for (int i = 0; i < getParameters().getVmsCount(); i++) {
      String currentVmName = generateUniqueVmName();
      VdcReturnValueBase returnValue =
          runInternalAction(
              VdcActionType.AddVmAndAttachToPool,
              buildAddVmAndAttachToPoolParameters(poolId, currentVmName),
              createAddVmStepContext(currentVmName));

      if (returnValue != null
          && !returnValue.getSucceeded()
          && !returnValue.getCanDoActionMessages().isEmpty()) {
        for (String msg : returnValue.getCanDoActionMessages()) {
          if (!getReturnValue().getCanDoActionMessages().contains(msg)) {
            getReturnValue().getCanDoActionMessages().add(msg);
          }
        }
        addVmsSucceeded = false;
        subsequentFailedAttempts++;
      } else { // Succeed on that , reset subsequentFailedAttempts.
        subsequentFailedAttempts = 0;
        vmsAdded = true;
      }
      // if subsequent attempts failure exceeds configuration value , abort the loop.
      if (subsequentFailedAttempts == vmPoolMaxSubsequentFailures) {
        AuditLogableBase logable = new AuditLogableBase();
        auditLogDirector.log(logable, AuditLogType.USER_VM_POOL_MAX_SUBSEQUENT_FAILURES_REACHED);
        break;
      }
    }
  }
  public static Map<String, String> createStructFromConnection(
      final StorageServerConnections connection, final StoragePool storagePool) {
    // for information, see _connectionDict2ConnectionInfo in vdsm/storage/hsm.py
    DefaultValueMap con = new DefaultValueMap();
    con.put("id", connection.getid(), Guid.Empty.toString());
    con.put("connection", connection.getconnection(), "");
    con.put("tpgt", connection.getportal(), "");
    con.put("port", connection.getport(), "");
    con.put("iqn", connection.getiqn(), "");
    con.put("user", connection.getuser_name(), "");
    con.put("password", connection.getpassword(), "");
    con.putIfNotEmpty("ifaceName", connection.getIface());

    // storage_pool can be null when discovering iscsi send targets or when connecting
    // through vds which has no storage pool
    if (storagePool == null
        || Config.<Boolean>getValue(
            ConfigValues.AdvancedNFSOptionsEnabled,
            storagePool.getcompatibility_version().getValue())) {
      // For mnt_options, vfs_type, and protocol_version - if they are null
      // or empty we should not send a key with an empty value
      con.putIfNotEmpty("mnt_options", connection.getMountOptions());
      con.putIfNotEmpty("vfs_type", connection.getVfsType());
      if (connection.getNfsVersion() != null) {
        con.put("protocol_version", connection.getNfsVersion().getValue());
      }
      con.putIfNotEmpty("timeout", connection.getNfsTimeo());
      con.putIfNotEmpty("retrans", connection.getNfsRetrans());
    }
    return con;
  }
Ejemplo n.º 7
0
  protected void executeHttpMethod(final T method) {
    int responseCode = -1;
    VdsManager manager = ResourceManager.getInstance().getVdsManager(getParameters().getVdsId());
    final HttpClient httpclient = manager.getVdsProxy().getHttpClient();
    try {
      FutureTask<Integer> futureTask =
          new FutureTask(
              new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                  return httpclient.executeMethod(method);
                }
              });
      Future<Integer> f = ThreadPoolUtil.execute(futureTask);
      if (f.get(Config.<Integer>getValue(getConfigValueTimeLimitForOperation()), TimeUnit.MINUTES)
          == null) {
        responseCode = futureTask.get();
      }
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    } catch (Exception e) {
      log.debug("Exception", e);
      throw createNetworkException(e);
    }

    if (responseCode == getSuccessCode()) {
      Guid createdTask =
          Guid.createGuidFromString(processResponseHeaderValue(getMethod(), "Task-Id", null));
      getVDSReturnValue()
          .setCreationInfo(
              new AsyncTaskCreationInfo(
                  createdTask, getCreatedTaskType(), getParameters().getStoragePoolId()));
      handleOkResponse();
      getVDSReturnValue().setSucceeded(true);
      return;
    }

    processResponseHeaderValue(getMethod(), "Content-type", "application/json");

    String response;
    try {
      response = getMethod().getResponseBodyAsString();
    } catch (Exception e) {
      throw createNetworkException(e);
    }

    Map<String, Object> resultMap = null;
    try {
      resultMap = new ObjectMapper().readValue(response, HashMap.class);
      status = new StatusOnlyReturnForXmlRpc(resultMap);
    } catch (Exception e) {
      throwVdsErrorException("failed to parse response " + response, EngineError.GeneralException);
    }

    proceedProxyReturnValue();
  }
Ejemplo n.º 8
0
 private void addVdsStaticToDb() {
   getParameters()
       .getVdsStaticData()
       .setServerSslEnabled(Config.<Boolean>getValue(ConfigValues.EncryptHostCommunication));
   vdsStaticDao.save(getParameters().getVdsStaticData());
   getCompensationContext().snapshotNewEntity(getParameters().getVdsStaticData());
   setVdsIdRef(getParameters().getVdsStaticData().getId());
   addFenceAgents();
   setVds(null);
 }
  private static boolean shouldPerformRecoveryOnType(String type) {
    Map<String, String> allowedRecoveryTypesFromConfig =
        Config.<Map<String, String>>getValue(ConfigValues.AutoRecoveryAllowedTypes);
    String isAllowed = allowedRecoveryTypesFromConfig.get(type);
    if (isAllowed != null) {
      return Boolean.parseBoolean(isAllowed);
    }

    return true;
  }
  /**
   * This method is called upon the bean creation as part of the management Service bean life cycle.
   */
  @Override
  @PostConstruct
  public void create() {

    try {
      // This must be done before starting to sample the hosts status from VDSM since the sampling
      // will turn such host from Reboot to NonResponsive
      loadService(PmHealthCheckManager.class);
      loadService(EngineBackupAwarenessManager.class);
      CommandCoordinatorUtil.initAsyncTaskManager();
      loadService(ResourceManager.class);
      OvfDataUpdater.getInstance().initOvfDataUpdater();
      ThreadPoolUtil.execute(
          new Runnable() {
            @Override
            public void run() {
              MacPoolPerDcSingleton.getInstance().initialize();
            }
          });
      StoragePoolStatusHandler.init();

      GlusterJobsManager.init();

      try {
        log.info("Init VM custom properties utilities");
        VmPropertiesUtils.getInstance().init();
      } catch (InitializationException e) {
        log.error("Initialization of vm custom properties failed.", e);
      }

      try {
        log.info("Init device custom properties utilities");
        DevicePropertiesUtils.getInstance().init();
      } catch (InitializationException e) {
        log.error("Initialization of device custom properties failed.", e);
      }

      loadService(SchedulingManager.class);

      SessionDataContainer.getInstance().cleanupEngineSessionsOnStartup();

      loadService(HostDeviceManager.class);
      loadService(DwhHeartBeat.class);

      if (Config.<Boolean>getValue(ConfigValues.AffinityRulesEnforcementManagerEnabled)) {
        loadService(AffinityRulesEnforcementManager.class);
      }

      loadService(CertificationValidityChecker.class);
    } catch (Exception ex) {
      log.error("Failed to initialize backend", ex);
      throw ex;
    }
  }
 /** 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());
 }
Ejemplo n.º 12
0
 /**
  * getInstalledVdsIdIfExists
  *
  * <p>Communicate with host by SSH session and gather vdsm-id if exist
  *
  * @param client - already connected ssh client
  */
 private String getInstalledVdsIdIfExists(SSHClient client) {
   try {
     ByteArrayOutputStream out = new ConstraintByteArrayOutputStream(256);
     client.executeCommand(
         Config.<String>getValue(ConfigValues.GetVdsmIdByVdsmToolCommand), null, out, null);
     return new String(out.toByteArray(), StandardCharsets.UTF_8);
   } catch (Exception e) {
     log.warn("Failed to initiate vdsm-id request on host: {}", e.getMessage());
     log.debug("Exception", e);
     return null;
   }
 }
Ejemplo n.º 13
0
  protected ValidationResult validateMemorySize(VM vm) {
    final ConfigValues configKey =
        getOsRepository().get64bitOss().contains(vm.getOs())
            ? ConfigValues.VM64BitMaxMemorySizeInMB
            : ConfigValues.VM32BitMaxMemorySizeInMB;
    final int maxSize = Config.getValue(configKey, vm.getVdsGroupCompatibilityVersion().getValue());
    if (vm.getMemSizeMb() > maxSize) {
      return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_MEMORY_EXCEEDS_SUPPORTED_LIMIT);
    }

    return ValidationResult.VALID;
  }
Ejemplo n.º 14
0
  private String getTimeZoneForVm(VM vm) {
    if (!StringUtils.isEmpty(vm.getTimeZone())) {
      return vm.getTimeZone();
    }

    // else fallback to engine config default for given OS type
    if (osRepository.isWindows(vm.getOs())) {
      return Config.<String>getValue(ConfigValues.DefaultWindowsTimeZone);
    } else {
      return "Etc/GMT";
    }
  }
Ejemplo n.º 15
0
 private void addCpuPinning(final String compatibilityVersion) {
   final String cpuPinning = vm.getCpuPinning();
   if (StringUtils.isNotEmpty(cpuPinning)
       && Boolean.TRUE.equals(
           Config.<Boolean>getValue(ConfigValues.CpuPinningEnabled, compatibilityVersion))) {
     final Map<String, Object> pinDict = new HashMap<String, Object>();
     for (String pin : cpuPinning.split("_")) {
       final String[] split = pin.split("#");
       pinDict.put(split[0], split[1]);
     }
     createInfo.put(VdsProperties.cpuPinning, pinDict);
   }
 }
Ejemplo n.º 16
0
 private void addVdsDynamicToDb() {
   VdsDynamic vdsDynamic = new VdsDynamic();
   vdsDynamic.setId(getParameters().getVdsStaticData().getId());
   // TODO: oVirt type - here oVirt behaves like power client?
   if (getParameters().isPending()) {
     vdsDynamic.setStatus(VDSStatus.PendingApproval);
   } else if (getParameters().isProvisioned()) {
     vdsDynamic.setStatus(VDSStatus.InstallingOS);
   } else if (Config.<Boolean>getValue(ConfigValues.InstallVds)) {
     vdsDynamic.setStatus(VDSStatus.Installing);
   }
   vdsDynamicDao.save(vdsDynamic);
   getCompensationContext().snapshotNewEntity(vdsDynamic);
 }
Ejemplo n.º 17
0
  private Boolean getMigrateCompressed() {
    if (FeatureSupported.migrationCompression(getVm().getVdsGroupCompatibilityVersion())) {
      if (getVm().getMigrateCompressed() != null) {
        return getVm().getMigrateCompressed();
      }

      if (getVdsGroup().getMigrateCompressed() != null) {
        return getVdsGroup().getMigrateCompressed();
      }

      return Config.getValue(ConfigValues.DefaultMigrationCompression);
    }

    return null;
  }
Ejemplo n.º 18
0
  private Boolean getAutoConverge() {
    if (FeatureSupported.autoConvergence(getVm().getVdsGroupCompatibilityVersion())) {
      if (getVm().getAutoConverge() != null) {
        return getVm().getAutoConverge();
      }

      if (getVdsGroup().getAutoConverge() != null) {
        return getVdsGroup().getAutoConverge();
      }

      return Config.getValue(ConfigValues.DefaultAutoConvergence);
    }

    return null;
  }
Ejemplo n.º 19
0
  protected T getMethod() {
    if (method == null) {
      VdsStatic vdsStatic = getAndSetVdsStatic();

      Pair<String, URL> urlInfo =
          XmlRpcUtils.getConnectionUrl(
              vdsStatic.getHostName(),
              vdsStatic.getPort(),
              "",
              Config.<Boolean>getValue(ConfigValues.EncryptHostCommunication));

      method = concreteCreateMethod(urlInfo.getFirst());
    }

    return method;
  }
Ejemplo n.º 20
0
  @Override
  protected boolean validate() {
    boolean retVal = super.validate();

    if (retVal) {
      StoragePool storagePool =
          DbFacade.getInstance().getStoragePoolDao().getForVds(getParameters().getVdsId());

      if (storagePool == null) {
        addValidationMessage(EngineMessage.NETWORK_CLUSTER_HAVE_NOT_EXISTING_DATA_CENTER_NETWORK);
        retVal = false;
      } else {
        setStoragePool(storagePool);
      }

      if (retVal
          && getStorageDomain().getStorageType() == StorageType.LOCALFS
          && !storagePool.isLocal()) {
        addValidationMessage(EngineMessage.ACTION_TYPE_FAILED_STORAGE_POOL_IS_NOT_LOCAL);
        retVal = false;
      }

      if (retVal && storagePool.getStatus() != StoragePoolStatus.Uninitialized) {
        retVal = checkMasterDomainIsUp();
      }

      // we limit RHEV-H local storage to its persistence mount - /data/images/rhev/
      if (retVal && this.getVds().isOvirtNode()) {

        StorageServerConnections conn =
            DbFacade.getInstance()
                .getStorageServerConnectionDao()
                .get(getParameters().getStorageDomain().getStorage());

        String rhevhLocalFSPath = Config.<String>getValue(ConfigValues.RhevhLocalFSPath);
        if (!conn.getConnection().equals(rhevhLocalFSPath)) {
          addValidationMessage(EngineMessage.RHEVH_LOCALFS_WRONG_PATH_LOCATION);
          addValidationMessageVariable("path", rhevhLocalFSPath);
          retVal = false;
        }
      }
    }
    return retVal;
  }
Ejemplo n.º 21
0
  private static VDSReturnValue runVdsCommand(
      VDSCommandType vdsCommandType,
      VdsIdVDSCommandParametersBase params,
      Guid storagePoolId,
      CommandBase<?> cmd,
      boolean performFailover) {
    Set<Guid> executedHosts = new HashSet<>();
    VDSReturnValue returnValue = null;
    if (params.getVdsId() == null) {
      chooseHostForExecution(params, storagePoolId, cmd, Collections.emptyList());
      if (params.getVdsId() == null) {
        throw new EngineException(
            EngineError.RESOURCE_MANAGER_VDS_NOT_FOUND,
            "No host was found to perform the operation");
      }
    }

    int attempts = 0;
    while (attempts <= Config.<Integer>getValue(ConfigValues.HsmCommandFailOverRetries)) {
      try {
        attempts++;
        returnValue = getBackend().getResourceManager().runVdsCommand(vdsCommandType, params);
        if (returnValue != null && returnValue.getSucceeded()) {
          return returnValue;
        }
      } catch (EngineException e) {
        returnValue = e.getVdsReturnValue();
      }

      executedHosts.add(params.getVdsId());

      if (!performFailover || (returnValue != null && !returnValue.isCanTryOnDifferentVds())) {
        break;
      }

      chooseHostForExecution(params, storagePoolId, cmd, executedHosts);

      if (params.getVdsId() == null) {
        break;
      }
    }

    return VdsHandler.handleVdsResult(returnValue);
  }
Ejemplo n.º 22
0
  private void cleanZombieTasks() {
    long maxTime =
        DateTime.getNow()
            .addMinutes(
                -1 * Config.<Integer>getValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes))
            .getTime();
    for (SPMTask task : _tasks.values()) {

      if (task.getParameters().getDbAsyncTask().getStartTime().getTime() < maxTime) {
        AuditLogableBase logable = Injector.injectMembers(new AuditLogableBase());
        logable.addCustomValue(
            "CommandName", task.getParameters().getDbAsyncTask().getActionType().toString());
        logable.addCustomValue(
            "Date", task.getParameters().getDbAsyncTask().getStartTime().toString());

        // if task is not finish and not unknown then it's in running
        // status
        if (task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.finished
            && task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.unknown) {
          // mark it as a zombie task, Will result in failure of the command
          task.setZombieTask(true);
          auditLogDirector.log(logable, AuditLogType.TASK_STOPPING_ASYNC_TASK);

          log.info(
              "Cleaning zombie tasks: Stopping async task '{}' that started at '{}'",
              task.getParameters().getDbAsyncTask().getActionType(),
              task.getParameters().getDbAsyncTask().getStartTime());

          task.stopTask(true);
        } else {
          auditLogDirector.log(logable, AuditLogType.TASK_CLEARING_ASYNC_TASK);

          log.info(
              "Cleaning zombie tasks: Clearing async task '{}' that started at '{}'",
              task.getParameters().getDbAsyncTask().getActionType(),
              task.getParameters().getDbAsyncTask().getStartTime());

          task.clearAsyncTask(true);
        }
      }
    }
  }
Ejemplo n.º 23
0
  protected void processExternallyManagedVms() {
    // Fetching for details from the host
    // and marking the VMs for addition
    List<String> vmsToQuery = new ArrayList<>(externalVms.size());
    for (Pair<VM, VmInternalData> pair : externalVms) {
      vmsToQuery.add(pair.getSecond().getVmDynamic().getId().toString());
    }
    if (!vmsToQuery.isEmpty()) {
      // Query VDSM for VMs info, and creating a proper VMStatic to be used when importing them
      Map[] vmsInfo = getVmInfo(vmsToQuery);
      for (Map vmInfo : vmsInfo) {
        Guid vmId = Guid.createGuidFromString((String) vmInfo.get(VdsProperties.vm_guid));
        VmStatic vmStatic = new VmStatic();
        vmStatic.setId(vmId);
        vmStatic.setCreationDate(new Date());
        vmStatic.setVdsGroupId(vdsManager.getVdsGroupId());
        String vmNameOnHost = (String) vmInfo.get(VdsProperties.vm_name);

        if (StringUtils.equals(
            Config.<String>getValue(ConfigValues.HostedEngineVmName), vmNameOnHost)) {
          // its a hosted engine VM -> import it and skip the external VM phase
          importHostedEngineVM(vmInfo);
          continue;
        } else {
          vmStatic.setName(String.format(EXTERNAL_VM_NAME_FORMAT, vmNameOnHost));
          vmStatic.setOrigin(OriginType.EXTERNAL);
        }

        vmStatic.setNumOfSockets(
            VdsBrokerObjectsBuilder.parseIntVdsProperty(vmInfo.get(VdsProperties.num_of_cpus)));
        vmStatic.setMemSizeMb(
            VdsBrokerObjectsBuilder.parseIntVdsProperty(vmInfo.get(VdsProperties.mem_size_mb)));
        vmStatic.setSingleQxlPci(false);

        externalVmsToAdd.add(vmStatic);
        log.info(
            "Importing VM '{}' as '{}', as it is running on the on Host, but does not exist in the engine.",
            vmNameOnHost,
            vmStatic.getName());
      }
    }
  }
Ejemplo n.º 24
0
  @OnTimerMethodAnnotation("timerElapsed")
  public synchronized void timerElapsed() {
    if (thereAreTasksToPoll()) {
      pollAndUpdateAsyncTasks();

      if (thereAreTasksToPoll() && logChangedMap) {
        log.info(
            "Finished polling Tasks, will poll again in {} seconds.",
            Config.<Integer>getValue(ConfigValues.AsyncTaskPollingRate));

        // Set indication to false for not logging the same message next
        // time.
        logChangedMap = false;
      }

      // check for zombie tasks
      if (_tasks.size() > 0) {
        cleanZombieTasks();
      }
    }
  }
Ejemplo n.º 25
0
  protected boolean canConnect(VDS vds) {
    // execute the connectivity and id uniqueness validation for VDS type hosts
    if (!getParameters().isPending()
        && !getParameters().isProvisioned()
        && Config.<Boolean>getValue(ConfigValues.InstallVds)) {
      try (final EngineSSHClient sshclient = getSSHClient()) {
        sshclient.connect();
        sshclient.authenticate();

        String hostUUID = getInstalledVdsIdIfExists(sshclient);
        if (hostUUID != null && vdsDao.getAllWithUniqueId(hostUUID).size() != 0) {
          return failValidation(EngineMessage.ACTION_TYPE_FAILED_VDS_WITH_SAME_UUID_EXIST);
        }

        return isValidGlusterPeer(sshclient, vds.getClusterId());
      } catch (AuthenticationException e) {
        log.error(
            "Failed to authenticate session with host '{}': {}", vds.getName(), e.getMessage());
        log.debug("Exception", e);
        return failValidation(EngineMessage.VDS_CANNOT_AUTHENTICATE_TO_SERVER);
      } catch (SecurityException e) {
        log.error(
            "Failed to connect to host '{}', fingerprint '{}': {}",
            vds.getName(),
            vds.getSshKeyFingerprint(),
            e.getMessage());
        log.debug("Exception", e);
        addValidationMessage(EngineMessage.VDS_SECURITY_CONNECTION_ERROR);
        addValidationMessageVariable("ErrorMessage", e.getMessage());
        return failValidation(EngineMessage.VDS_CANNOT_AUTHENTICATE_TO_SERVER);
      } catch (Exception e) {
        log.error("Failed to establish session with host '{}': {}", vds.getName(), e.getMessage());
        log.debug("Exception", e);

        return failValidation(EngineMessage.VDS_CANNOT_CONNECT_TO_SERVER);
      }
    }
    return true;
  }
Ejemplo n.º 26
0
  public EngineSSHClient getSSHClient() throws Exception {
    Long timeout =
        TimeUnit.SECONDS.toMillis(
            Config.<Integer>getValue(ConfigValues.ConnectToServerTimeoutInSeconds));

    EngineSSHClient sshclient = new EngineSSHClient();
    sshclient.setVds(getParameters().getvds());
    sshclient.setHardTimeout(timeout);
    sshclient.setSoftTimeout(timeout);
    sshclient.setPassword(getParameters().getPassword());
    switch (getParameters().getAuthMethod()) {
      case PublicKey:
        sshclient.useDefaultKeyPair();
        break;
      case Password:
        sshclient.setPassword(getParameters().getPassword());
        break;
      default:
        throw new Exception("Invalid authentication method value was sent to AddVdsCommand");
    }

    return sshclient;
  }
Ejemplo n.º 27
0
 public static Integer getDefaultMtu() {
   return Config.<Integer>getValue(ConfigValues.DefaultMTU);
 }
  protected boolean reconstructMaster() {
    isLastMaster = proceedStorageDomainTreatmentByDomainType(getNewMasterStorageDomain(), false);

    // To issue a reconstructMaster you need to set the domain inactive unless the selected domain
    // is the current master
    if (getParameters().isInactive()
        && !getStorageDomain().getId().equals(getNewMasterStorageDomainId())) {
      executeInNewTransaction(
          () -> {
            setStorageDomainStatus(StorageDomainStatus.Inactive, getCompensationContext());
            calcStoragePoolStatusByDomainsStatus();
            getCompensationContext().stateChanged();
            return null;
          });
    }

    if (isLastMaster) {
      return stopSpm();
    }

    boolean commandSucceeded = stopSpm();

    final List<String> disconnectPoolFormats =
        Config.getValue(ConfigValues.DisconnectPoolOnReconstruct);

    if (commandSucceeded
        && disconnectPoolFormats.contains(
            getNewMasterStorageDomain().getStorageFormat().getValue())) {
      commandSucceeded =
          runVdsCommand(
                  VDSCommandType.DisconnectStoragePool,
                  new DisconnectStoragePoolVDSCommandParameters(
                      getVds().getId(), getStoragePool().getId(), getVds().getVdsSpmId()))
              .getSucceeded();
    }

    if (!commandSucceeded) {
      return false;
    }

    List<StoragePoolIsoMap> domains =
        storagePoolIsoMapDao.getAllForStoragePool(getStoragePool().getId());

    // set to true here in case of failure in executing/getting answer from the reconstruct vds
    // command,
    // unless we know that the command failed we assume that it succeeded (use by
    // RecoveryStoragePool command in
    // order to avoid detaching domain that is already part of the pool in vdsm).
    setActionReturnValue(true);
    return runVdsCommand(
            VDSCommandType.ReconstructMaster,
            new ReconstructMasterVDSCommandParameters(
                getVds().getId(),
                getVds().getVdsSpmId(),
                getStoragePool().getId(),
                getStoragePool().getName(),
                getNewMasterStorageDomainId(),
                domains,
                getStoragePool().getMasterDomainVersion()))
        .getSucceeded();
  }
Ejemplo n.º 29
0
  protected void buildVmProperties() {
    createInfo.put(VdsProperties.vm_guid, vm.getId().toString());
    createInfo.put(VdsProperties.vm_name, vm.getName());
    createInfo.put(VdsProperties.mem_size_mb, vm.getVmMemSizeMb());
    createInfo.put(VdsProperties.mem_guaranteed_size_mb, vm.getMinAllocatedMem());
    createInfo.put(VdsProperties.smartcardEnabled, Boolean.toString(vm.isSmartcardEnabled()));
    createInfo.put(VdsProperties.num_of_cpus, String.valueOf(vm.getNumOfCpus()));
    if (Config.<Boolean>getValue(ConfigValues.SendSMPOnRunVm)) {
      createInfo.put(VdsProperties.cores_per_socket, (Integer.toString(vm.getCpuPerSocket())));
      if (FeatureSupported.supportedInConfig(
          ConfigValues.HotPlugCpuSupported,
          vm.getVdsGroupCompatibilityVersion(),
          vm.getClusterArch())) {
        createInfo.put(
            VdsProperties.max_number_of_cpus,
            String.valueOf(
                Config.<Integer>getValue(
                    ConfigValues.MaxNumOfVmCpus, vm.getVdsGroupCompatibilityVersion().getValue())));
      }
    }
    final String compatibilityVersion = vm.getVdsGroupCompatibilityVersion().toString();
    addCpuPinning(compatibilityVersion);
    createInfo.put(VdsProperties.emulatedMachine, getVdsGroup().getEmulatedMachine());
    // send cipher suite and spice secure channels parameters only if ssl
    // enabled.
    if (Config.<Boolean>getValue(ConfigValues.SSLEnabled)) {
      createInfo.put(
          VdsProperties.spiceSslCipherSuite, Config.<String>getValue(ConfigValues.CipherSuite));
      createInfo.put(
          VdsProperties.SpiceSecureChannels,
          Config.<String>getValue(ConfigValues.SpiceSecureChannels, compatibilityVersion));
    }
    createInfo.put(VdsProperties.kvmEnable, vm.getKvmEnable().toString().toLowerCase());
    createInfo.put(VdsProperties.acpiEnable, vm.getAcpiEnable().toString().toLowerCase());

    createInfo.put(
        VdsProperties.Custom,
        VmPropertiesUtils.getInstance()
            .getVMProperties(vm.getVdsGroupCompatibilityVersion(), vm.getStaticData()));
    createInfo.put(VdsProperties.vm_type, "kvm"); // "qemu", "kvm"
    if (vm.isRunAndPause()) {
      createInfo.put(VdsProperties.launch_paused_param, "true");
    }
    if (vm.isUseHostCpuFlags()) {
      createInfo.put(VdsProperties.cpuType, "hostPassthrough");
    } else if (vm.getVdsGroupCpuFlagsData() != null) {
      createInfo.put(VdsProperties.cpuType, vm.getVdsGroupCpuFlagsData());
    }
    createInfo.put(VdsProperties.niceLevel, String.valueOf(vm.getNiceLevel()));
    if (vm.getCpuShares() > 0) {
      createInfo.put(VdsProperties.cpuShares, String.valueOf(vm.getCpuShares()));
    }
    if (!StringUtils.isEmpty(vm.getHibernationVolHandle())) {
      createInfo.put(VdsProperties.hiberVolHandle, vm.getHibernationVolHandle());
    }

    String keyboardLayout = vm.getDynamicData().getVncKeyboardLayout();
    if (keyboardLayout == null) {
      keyboardLayout = vm.getDefaultVncKeyboardLayout();
      if (keyboardLayout == null) {
        keyboardLayout = Config.<String>getValue(ConfigValues.VncKeyboardLayout);
      }
    }

    createInfo.put(VdsProperties.KeyboardLayout, keyboardLayout);
    if (osRepository.isLinux(vm.getVmOsId())) {
      createInfo.put(VdsProperties.PitReinjection, "false");
    }

    if (vm.getDisplayType() == DisplayType.vnc) {
      createInfo.put(VdsProperties.TabletEnable, "true");
    }
    createInfo.put(
        VdsProperties.transparent_huge_pages, vm.isTransparentHugePages() ? "true" : "false");
  }
Ejemplo n.º 30
0
  protected void readGeneralData() {
    XmlNode content = selectSingleNode(_document, "//*/Content");
    XmlNode node;
    vmBase.setVmInit(new VmInit());

    // set ovf version to the ovf object
    vmBase.setOvfVersion(getVersion());

    node = selectSingleNode(content, OvfProperties.DESCRIPTION);
    if (node != null) {
      vmBase.setDescription(node.innerText);
    }

    node = selectSingleNode(content, OvfProperties.COMMENT);
    if (node != null) {
      vmBase.setComment(node.innerText);
    }

    node = selectSingleNode(content, OvfProperties.DOMAIN);
    if (node != null) {
      vmBase.getVmInit().setDomain(node.innerText);
    }

    node = selectSingleNode(content, OvfProperties.CREATION_DATE);
    if (node != null) {
      Date creationDate = OvfParser.utcDateStringToLocaDate(node.innerText);
      if (creationDate != null) {
        vmBase.setCreationDate(creationDate);
      }
    }

    node = selectSingleNode(content, OvfProperties.EXPORT_DATE);
    if (node != null) {
      Date exportDate = OvfParser.utcDateStringToLocaDate(node.innerText);
      if (exportDate != null) {
        vmBase.setExportDate(exportDate);
      }
    }

    node = selectSingleNode(content, OvfProperties.DEFAULT_BOOT_SEQUENCE);
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setDefaultBootSequence(BootSequence.forValue(Integer.parseInt(node.innerText)));
      }
    }

    node = selectSingleNode(content, OvfProperties.INITRD_URL);
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setInitrdUrl(node.innerText);
      }
    }

    node = selectSingleNode(content, OvfProperties.KERNEL_URL);
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setKernelUrl(node.innerText);
      }
    }

    node = selectSingleNode(content, OvfProperties.KERNEL_PARAMS);
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setKernelParams(node.innerText);
      }
    }

    node = selectSingleNode(content, OvfProperties.GENERATION);
    if (node != null) {
      vmBase.setDbGeneration(Long.parseLong(node.innerText));
    } else {
      vmBase.setDbGeneration(1L);
    }

    node = selectSingleNode(content, OvfProperties.CUSTOM_COMPATIBILITY_VERSION);
    if (node != null) {
      vmBase.setCustomCompatibilityVersion(new Version(node.innerText));
    }

    Version originVersion = new Version(getVersion()); // the originating ENGINE version
    node = selectSingleNode(content, OvfProperties.CLUSTER_COMPATIBILITY_VERSION);
    if (node != null) {
      originVersion = new Version(node.innerText);
    }
    vmBase.setClusterCompatibilityVersionOrigin(originVersion);

    // Note: the fetching of 'default display type' should happen before reading
    // the hardware section
    node = selectSingleNode(content, getDefaultDisplayTypeStringRepresentation());
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setDefaultDisplayType(DisplayType.forValue(Integer.parseInt(node.innerText)));
      }
    }

    XmlNodeList list = selectNodes(content, "Section");

    if (list != null) {
      // The Os need to be read before the hardware
      node = getNode(list, "xsi:type", "ovf:OperatingSystemSection_Type");
      if (node != null) {
        readOsSection(node);
        if (!osRepository.isLinux(vmBase.getOsId())
            || vmBase.getDefaultDisplayType() != DisplayType.qxl) {
          vmBase.setSingleQxlPci(false);
        }
      }

      node = getNode(list, "xsi:type", "ovf:VirtualHardwareSection_Type");
      if (node != null) {
        readHardwareSection(node);
      }

      node = getNode(list, "xsi:type", "ovf:SnapshotsSection_Type");
      if (node != null) {
        readSnapshotsSection(node);
      }
    }

    // after reading the hardware section, if graphics device is still absent, add a default one
    addDefaultGraphicsDevice();
    // if boot order is not set, figure out some default based on the set of bootable disks
    setDefaultBootDevice();

    // due to dependency on vmBase.getOsId() must be read AFTER readOsSection
    node = selectSingleNode(content, OvfProperties.TIMEZONE);
    if (node != null && StringUtils.isNotEmpty(node.innerText)) {
      vmBase.setTimeZone(node.innerText);
    } else {
      if (osRepository.isWindows(vmBase.getOsId())) {
        vmBase.setTimeZone(Config.<String>getValue(ConfigValues.DefaultWindowsTimeZone));
      } else {
        vmBase.setTimeZone(Config.<String>getValue(ConfigValues.DefaultGeneralTimeZone));
      }
    }

    node = selectSingleNode(content, OvfProperties.ORIGIN);
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setOrigin(OriginType.forValue(Integer.parseInt(node.innerText)));
      }
    }

    node = selectSingleNode(content, OvfProperties.VM_TYPE);
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setVmType(VmType.forValue(Integer.parseInt(node.innerText)));
      }
    }

    node = selectSingleNode(content, OvfProperties.IS_SMARTCARD_ENABLED);
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setSmartcardEnabled(Boolean.parseBoolean(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.NUM_OF_IOTHREADS);
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setNumOfIoThreads(Integer.parseInt(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.DELETE_PROTECTED);
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setDeleteProtected(Boolean.parseBoolean(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.SSO_METHOD);
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setSsoMethod(SsoMethod.fromString(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.TUNNEL_MIGRATION);
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setTunnelMigration(Boolean.parseBoolean(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.VNC_KEYBOARD_LAYOUT);
    if (node != null) {
      if (!StringUtils.isEmpty(node.innerText)) {
        vmBase.setVncKeyboardLayout(node.innerText);
      }
    }

    node = selectSingleNode(content, OvfProperties.MIN_ALLOCATED_MEMORY);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setMinAllocatedMem(Integer.parseInt(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.IS_STATELESS);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setStateless(Boolean.parseBoolean(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.IS_RUN_AND_PAUSE);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setRunAndPause(Boolean.parseBoolean(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.CREATED_BY_USER_ID);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setCreatedByUserId(Guid.createGuidFromString(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.MIGRATION_DOWNTIME);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setMigrationDowntime(Integer.parseInt(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.MIGRATION_SUPPORT);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        MigrationSupport migrationSupport =
            MigrationSupport.forValue(Integer.parseInt(node.innerText));
        vmBase.setMigrationSupport(migrationSupport);
      }
    }

    // TODO dedicated to multiple hosts
    readDedicatedHostsList();

    node = selectSingleNode(content, OvfProperties.SERIAL_NUMBER_POLICY);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setSerialNumberPolicy(SerialNumberPolicy.forValue(Integer.parseInt(node.innerText)));
      }
    }

    node = selectSingleNode(content, OvfProperties.CUSTOM_SERIAL_NUMBER);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setCustomSerialNumber(node.innerText);
      }
    }

    node = selectSingleNode(content, OvfProperties.AUTO_STARTUP);
    if (node != null) {
      vmBase.setAutoStartup(Boolean.parseBoolean(node.innerText));
    }

    node = selectSingleNode(content, OvfProperties.PRIORITY);
    if (node != null) {
      vmBase.setPriority(Integer.parseInt(node.innerText));
    }

    node = selectSingleNode(content, OvfProperties.IS_BOOT_MENU_ENABLED);
    if (node != null) {
      vmBase.setBootMenuEnabled(Boolean.parseBoolean(node.innerText));
    }

    node = selectSingleNode(content, OvfProperties.IS_SPICE_FILE_TRANSFER_ENABLED);
    if (node != null) {
      vmBase.setSpiceFileTransferEnabled(Boolean.parseBoolean(node.innerText));
    }

    node = selectSingleNode(content, OvfProperties.IS_SPICE_COPY_PASTE_ENABLED);
    if (node != null) {
      vmBase.setSpiceCopyPasteEnabled(Boolean.parseBoolean(node.innerText));
    }

    node = selectSingleNode(content, OvfProperties.ALLOW_CONSOLE_RECONNECT);
    if (node != null) {
      vmBase.setAllowConsoleReconnect(Boolean.parseBoolean(node.innerText));
    }

    node = selectSingleNode(content, OvfProperties.IS_AUTO_CONVERGE);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setAutoConverge(Boolean.parseBoolean(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.IS_MIGRATE_COMPRESSED);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setMigrateCompressed(Boolean.parseBoolean(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.MIGRATION_POLICY_ID);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setMigrationPolicyId(Guid.createGuidFromString(node.innerText));
      }
    }

    node = selectSingleNode(content, OvfProperties.CUSTOM_EMULATED_MACHINE);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setCustomEmulatedMachine(node.innerText);
      }
    }

    node = selectSingleNode(content, OvfProperties.CUSTOM_CPU_NAME);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setCustomCpuName(node.innerText);
      }
    }

    node = selectSingleNode(content, OvfProperties.PREDEFINED_PROPERTIES);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setPredefinedProperties(node.innerText);
      }
    }

    node = selectSingleNode(content, OvfProperties.USER_DEFINED_PROPERTIES);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setUserDefinedProperties(node.innerText);
      }
    }

    node = selectSingleNode(content, OvfProperties.MAX_MEMORY_SIZE_MB);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setMaxMemorySizeMb(Integer.parseInt(node.innerText));
      }
    }

    vmBase.setCustomProperties(
        VmPropertiesUtils.getInstance()
            .customProperties(vmBase.getPredefinedProperties(), vmBase.getUserDefinedProperties()));

    node = selectSingleNode(content, OvfProperties.VM_LEASE);
    if (node != null) {
      if (StringUtils.isNotEmpty(node.innerText)) {
        vmBase.setLeaseStorageDomainId(new Guid(node.innerText));
      }
    }

    readGeneralData(content);

    readVmInit(content);
  }