<commit_before>package org.ovirt.engine.core.bll.validator;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.bll.ImagesHandler;
import org.ovirt.engine.core.bll.IsoDomainListSyncronizer;
import org.ovirt.engine.core.bll.ValidationResult;
import org.ovirt.engine.core.bll.VdsSelector;
import org.ovirt.engine.core.bll.VmHandler;
import org.ovirt.engine.core.bll.interfaces.BackendInternal;
import org.ovirt.engine.core.bll.snapshots.SnapshotsValidator;
import org.ovirt.engine.core.bll.storage.StoragePoolValidator;
import org.ovirt.engine.core.common.VdcActionUtils;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.BootSequence;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.ImageFileType;
import org.ovirt.engine.core.common.businessentities.RepoFileMetaData;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.queries.GetImagesListParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.vdscommands.IsVmDuringInitiatingVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.StorageDomainDAO;
import org.ovirt.engine.core.dao.VdsDAO;
import org.ovirt.engine.core.dao.network.VmNetworkInterfaceDao;
import org.ovirt.engine.core.utils.vmproperties.VmPropertiesUtils;

public class RunVmValidator {

    public boolean validateVmProperties(VM vm, List<String> messages) {
        List<VmPropertiesUtils.ValidationError> validationErrors =
                getVmPropertiesUtils().validateVMProperties(
                        vm.getVdsGroupCompatibilityVersion(),
                        vm.getStaticData());

        if (!validationErrors.isEmpty()) {
            VmHandler.handleCustomPropertiesError(validationErrors, messages);
            return false;
        }

        return true;
    }

    public ValidationResult validateBootSequence(VM vm, BootSequence bootSequence, List<Disk> vmDisks) {
        BootSequence boot_sequence = (bootSequence != null) ?
                bootSequence : vm.getDefaultBootSequence();
        Guid storagePoolId = vm.getStoragePoolId();
        // Block from running a VM with no HDD when its first boot device is
        // HD and no other boot devices are configured
        if (boot_sequence == BootSequence.C && vmDisks.size() == 0) {
            return new ValidationResult(VdcBllMessages.VM_CANNOT_RUN_FROM_DISK_WITHOUT_DISK);
        } else {
            // If CD appears as first and there is no ISO in storage
            // pool/ISO inactive -
            // you cannot run this VM

            if (boot_sequence == BootSequence.CD
                    && getIsoDomainListSyncronizer().findActiveISODomain(storagePoolId) == null) {
                return new ValidationResult(VdcBllMessages.VM_CANNOT_RUN_FROM_CD_WITHOUT_ACTIVE_STORAGE_DOMAIN_ISO);
            } else {
                // if there is network in the boot sequence, check that the
                // vm has network,
                // otherwise the vm cannot be run in vdsm
                if (boot_sequence == BootSequence.N
                        && getVmNetworkInterfaceDao().getAllForVm(vm.getId()).size() == 0) {
                    return new ValidationResult(VdcBllMessages.VM_CANNOT_RUN_FROM_NETWORK_WITHOUT_NETWORK);
                }
            }
        }
        return ValidationResult.VALID;

    }

    /**
     * Check storage domains. Storage domain status and disk space are checked only for non-HA VMs.
     *
     * @param vm
     *            The VM to run
     * @param message
     *            The error messages to append to
     * @param isInternalExecution
     *            Command is internal?
     * @param vmImages
     *            The VM's image disks
     * @return <code>true</code> if the VM can be run, <code>false</code> if not
     */
    public boolean validateStorageDomains(VM vm,
            List<String> message,
            boolean isInternalExecution,
            List<DiskImage> vmImages) {
        if (!vm.isAutoStartup() || !isInternalExecution) {
            Set<Guid> storageDomainIds = ImagesHandler.getAllStorageIdsForImageIds(vmImages);
            MultipleStorageDomainsValidator storageDomainValidator =
                    new MultipleStorageDomainsValidator(vm.getStoragePoolId(), storageDomainIds);
            if (!validate(storageDomainValidator.allDomainsExistAndActive(), message)) {
                return false;
            }

            if (!vm.isAutoStartup()
                    && !validate(storageDomainValidator.allDomainsWithinThresholds(), message)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Check isValid only if VM is not HA VM
     */
    public boolean validateImagesForRunVm(List<String> message, List<DiskImage> vmDisks) {
        DiskImagesValidator diskImagesValidator = new DiskImagesValidator(vmDisks);
        return validate(diskImagesValidator.diskImagesNotLocked(), message);
    }

    @SuppressWarnings("unchecked")
    public ValidationResult validateIsoPath(boolean isAutoStartup,
            Guid storageDomainId,
            String diskPath,
            String floppyPath) {
        if (isAutoStartup) {
            return ValidationResult.VALID;
        }
        if (!StringUtils.isEmpty(diskPath)) {
            if (storageDomainId == null) {
                return new ValidationResult(VdcBllMessages.VM_CANNOT_RUN_FROM_CD_WITHOUT_ACTIVE_STORAGE_DOMAIN_ISO);
            }
            boolean retValForIso = false;
            VdcQueryReturnValue ret =
                    getBackend().runInternalQuery(VdcQueryType.GetImagesList,
                            new GetImagesListParameters(storageDomainId, ImageFileType.ISO));<commit_msg>core: Fix RunOnce from a CD-ROM<commit_after>package org.ovirt.engine.core.bll.validator;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.bll.ImagesHandler;
import org.ovirt.engine.core.bll.IsoDomainListSyncronizer;
import org.ovirt.engine.core.bll.ValidationResult;
import org.ovirt.engine.core.bll.VdsSelector;
import org.ovirt.engine.core.bll.VmHandler;
import org.ovirt.engine.core.bll.interfaces.BackendInternal;
import org.ovirt.engine.core.bll.snapshots.SnapshotsValidator;
import org.ovirt.engine.core.bll.storage.StoragePoolValidator;
import org.ovirt.engine.core.common.VdcActionUtils;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.BootSequence;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.ImageFileType;
import org.ovirt.engine.core.common.businessentities.RepoFileMetaData;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.queries.GetImagesListParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.vdscommands.IsVmDuringInitiatingVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.StorageDomainDAO;
import org.ovirt.engine.core.dao.VdsDAO;
import org.ovirt.engine.core.dao.network.VmNetworkInterfaceDao;
import org.ovirt.engine.core.utils.vmproperties.VmPropertiesUtils;

public class RunVmValidator {

    public boolean validateVmProperties(VM vm, List<String> messages) {
        List<VmPropertiesUtils.ValidationError> validationErrors =
                getVmPropertiesUtils().validateVMProperties(
                        vm.getVdsGroupCompatibilityVersion(),
                        vm.getStaticData());

        if (!validationErrors.isEmpty()) {
            VmHandler.handleCustomPropertiesError(validationErrors, messages);
            return false;
        }

        return true;
    }

    public ValidationResult validateBootSequence(VM vm, BootSequence bootSequence, List<Disk> vmDisks) {
        BootSequence boot_sequence = (bootSequence != null) ?
                bootSequence : vm.getDefaultBootSequence();
        Guid storagePoolId = vm.getStoragePoolId();
        // Block from running a VM with no HDD when its first boot device is
        // HD and no other boot devices are configured
        if (boot_sequence == BootSequence.C && vmDisks.size() == 0) {
            return new ValidationResult(VdcBllMessages.VM_CANNOT_RUN_FROM_DISK_WITHOUT_DISK);
        } else {
            // If CD appears as first and there is no ISO in storage
            // pool/ISO inactive -
            // you cannot run this VM

            if (boot_sequence == BootSequence.CD
                    && getIsoDomainListSyncronizer().findActiveISODomain(storagePoolId) == null) {
                return new ValidationResult(VdcBllMessages.VM_CANNOT_RUN_FROM_CD_WITHOUT_ACTIVE_STORAGE_DOMAIN_ISO);
            } else {
                // if there is network in the boot sequence, check that the
                // vm has network,
                // otherwise the vm cannot be run in vdsm
                if (boot_sequence == BootSequence.N
                        && getVmNetworkInterfaceDao().getAllForVm(vm.getId()).size() == 0) {
                    return new ValidationResult(VdcBllMessages.VM_CANNOT_RUN_FROM_NETWORK_WITHOUT_NETWORK);
                }
            }
        }
        return ValidationResult.VALID;

    }

    /**
     * Check storage domains. Storage domain status and disk space are checked only for non-HA VMs.
     *
     * @param vm
     *            The VM to run
     * @param message
     *            The error messages to append to
     * @param isInternalExecution
     *            Command is internal?
     * @param vmImages
     *            The VM's image disks
     * @return <code>true</code> if the VM can be run, <code>false</code> if not
     */
    public boolean validateStorageDomains(VM vm,
            List<String> message,
            boolean isInternalExecution,
            List<DiskImage> vmImages) {
        if (!vm.isAutoStartup() || !isInternalExecution) {
            Set<Guid> storageDomainIds = ImagesHandler.getAllStorageIdsForImageIds(vmImages);
            MultipleStorageDomainsValidator storageDomainValidator =
                    new MultipleStorageDomainsValidator(vm.getStoragePoolId(), storageDomainIds);
            if (!validate(storageDomainValidator.allDomainsExistAndActive(), message)) {
                return false;
            }

            if (!vm.isAutoStartup()
                    && !validate(storageDomainValidator.allDomainsWithinThresholds(), message)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Check isValid only if VM is not HA VM
     */
    public boolean validateImagesForRunVm(List<String> message, List<DiskImage> vmDisks) {
        DiskImagesValidator diskImagesValidator = new DiskImagesValidator(vmDisks);
        return validate(diskImagesValidator.diskImagesNotLocked(), message);
    }

    @SuppressWarnings("unchecked")
    public ValidationResult validateIsoPath(boolean isAutoStartup,
            Guid storagePoolId,
            String diskPath,
            String floppyPath) {
        if (isAutoStartup) {
            return ValidationResult.VALID;
        }

        Guid storageDomainId = getIsoDomainListSyncronizer().findActiveISODomain(storagePoolId);

        if (!StringUtils.isEmpty(diskPath)) {
            if (storageDomainId == null) {
                return new ValidationResult(VdcBllMessages.VM_CANNOT_RUN_FROM_CD_WITHOUT_ACTIVE_STORAGE_DOMAIN_ISO);
            }
            boolean retValForIso = false;
            VdcQueryReturnValue ret =
                    getBackend().runInternalQuery(VdcQueryType.GetImagesList,
                            new GetImagesListParameters(storageDomainId, ImageFileType.ISO));
{'fraction_non_alphanumeric': 0.0893052416709193, 'fraction_numerical': 0.0002916089523948385, 'mean_word_length': 2.89937464468448, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6725648', 'n_tokens_mistral': 3918, 'n_tokens_neox': 3856, 'n_words': 725}