Search in sources :

Example 26 with GuestOS

use of com.cloud.storage.GuestOS in project cloudstack by apache.

the class UnmanagedVMsManagerImpl method importUnmanagedInstance.

@Override
public UserVmResponse importUnmanagedInstance(ImportUnmanagedInstanceCmd cmd) {
    final Account caller = CallContext.current().getCallingAccount();
    if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
        throw new PermissionDeniedException(String.format("Cannot perform this operation, Calling account is not root admin: %s", caller.getUuid()));
    }
    final Long clusterId = cmd.getClusterId();
    if (clusterId == null) {
        throw new InvalidParameterValueException(String.format("Cluster ID cannot be null"));
    }
    final Cluster cluster = clusterDao.findById(clusterId);
    if (cluster == null) {
        throw new InvalidParameterValueException(String.format("Cluster ID: %d cannot be found", clusterId));
    }
    if (cluster.getHypervisorType() != Hypervisor.HypervisorType.VMware) {
        throw new InvalidParameterValueException(String.format("VM import is currently not supported for hypervisor: %s", cluster.getHypervisorType().toString()));
    }
    final DataCenter zone = dataCenterDao.findById(cluster.getDataCenterId());
    final String instanceName = cmd.getName();
    if (StringUtils.isEmpty(instanceName)) {
        throw new InvalidParameterValueException(String.format("Instance name cannot be empty"));
    }
    if (cmd.getDomainId() != null && StringUtils.isEmpty(cmd.getAccountName())) {
        throw new InvalidParameterValueException("domainid parameter must be specified with account parameter");
    }
    final Account owner = accountService.getActiveAccountById(cmd.getEntityOwnerId());
    long userId = CallContext.current().getCallingUserId();
    List<UserVO> userVOs = userDao.listByAccount(owner.getAccountId());
    if (CollectionUtils.isNotEmpty(userVOs)) {
        userId = userVOs.get(0).getId();
    }
    VMTemplateVO template = null;
    final Long templateId = cmd.getTemplateId();
    if (templateId == null) {
        template = templateDao.findByName(VM_IMPORT_DEFAULT_TEMPLATE_NAME);
        if (template == null) {
            template = createDefaultDummyVmImportTemplate();
            if (template == null) {
                throw new InvalidParameterValueException(String.format("Default VM import template with unique name: %s for hypervisor: %s cannot be created. Please use templateid paramter for import", VM_IMPORT_DEFAULT_TEMPLATE_NAME, cluster.getHypervisorType().toString()));
            }
        }
    } else {
        template = templateDao.findById(templateId);
    }
    if (template == null) {
        throw new InvalidParameterValueException(String.format("Template ID: %d cannot be found", templateId));
    }
    final Long serviceOfferingId = cmd.getServiceOfferingId();
    if (serviceOfferingId == null) {
        throw new InvalidParameterValueException(String.format("Service offering ID cannot be null"));
    }
    final ServiceOfferingVO serviceOffering = serviceOfferingDao.findById(serviceOfferingId);
    if (serviceOffering == null) {
        throw new InvalidParameterValueException(String.format("Service offering ID: %d cannot be found", serviceOfferingId));
    }
    accountService.checkAccess(owner, serviceOffering, zone);
    try {
        resourceLimitService.checkResourceLimit(owner, Resource.ResourceType.user_vm, 1);
    } catch (ResourceAllocationException e) {
        LOGGER.error(String.format("VM resource allocation error for account: %s", owner.getUuid()), e);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("VM resource allocation error for account: %s. %s", owner.getUuid(), StringUtils.defaultString(e.getMessage())));
    }
    String displayName = cmd.getDisplayName();
    if (StringUtils.isEmpty(displayName)) {
        displayName = instanceName;
    }
    String hostName = cmd.getHostName();
    if (StringUtils.isEmpty(hostName)) {
        if (!NetUtils.verifyDomainNameLabel(instanceName, true)) {
            throw new InvalidParameterValueException(String.format("Please provide hostname for the VM. VM name contains unsupported characters for it to be used as hostname"));
        }
        hostName = instanceName;
    }
    if (!NetUtils.verifyDomainNameLabel(hostName, true)) {
        throw new InvalidParameterValueException("Invalid VM hostname. VM hostname can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'), must be between 1 and 63 characters long, and can't start or end with \"-\" and can't start with digit");
    }
    if (cluster.getHypervisorType().equals(Hypervisor.HypervisorType.VMware) && Boolean.parseBoolean(configurationDao.getValue(Config.SetVmInternalNameUsingDisplayName.key()))) {
        // If global config vm.instancename.flag is set to true, then CS will set guest VM's name as it appears on the hypervisor, to its hostname.
        // In case of VMware since VM name must be unique within a DC, check if VM with the same hostname already exists in the zone.
        VMInstanceVO vmByHostName = vmDao.findVMByHostNameInZone(hostName, zone.getId());
        if (vmByHostName != null && vmByHostName.getState() != VirtualMachine.State.Expunging) {
            throw new InvalidParameterValueException(String.format("Failed to import VM: %s. There already exists a VM by the hostname: %s in zone: %s", instanceName, hostName, zone.getUuid()));
        }
    }
    final Map<String, Long> nicNetworkMap = cmd.getNicNetworkList();
    final Map<String, Network.IpAddresses> nicIpAddressMap = cmd.getNicIpAddressList();
    final Map<String, Long> dataDiskOfferingMap = cmd.getDataDiskToDiskOfferingList();
    final Map<String, String> details = cmd.getDetails();
    final boolean forced = cmd.isForced();
    List<HostVO> hosts = resourceManager.listHostsInClusterByStatus(clusterId, Status.Up);
    UserVm userVm = null;
    List<String> additionalNameFilters = getAdditionalNameFilters(cluster);
    for (HostVO host : hosts) {
        if (host.isInMaintenanceStates()) {
            continue;
        }
        List<String> managedVms = new ArrayList<>();
        managedVms.addAll(additionalNameFilters);
        managedVms.addAll(getHostManagedVms(host));
        GetUnmanagedInstancesCommand command = new GetUnmanagedInstancesCommand(instanceName);
        command.setManagedInstancesNames(managedVms);
        Answer answer = agentManager.easySend(host.getId(), command);
        if (!(answer instanceof GetUnmanagedInstancesAnswer)) {
            continue;
        }
        GetUnmanagedInstancesAnswer unmanagedInstancesAnswer = (GetUnmanagedInstancesAnswer) answer;
        HashMap<String, UnmanagedInstanceTO> unmanagedInstances = unmanagedInstancesAnswer.getUnmanagedInstances();
        if (MapUtils.isEmpty(unmanagedInstances)) {
            continue;
        }
        Set<String> names = unmanagedInstances.keySet();
        for (String name : names) {
            if (instanceName.equals(name)) {
                UnmanagedInstanceTO unmanagedInstance = unmanagedInstances.get(name);
                if (unmanagedInstance == null) {
                    throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Unable to retrieve details for unmanaged VM: %s", name));
                }
                if (template.getName().equals(VM_IMPORT_DEFAULT_TEMPLATE_NAME)) {
                    String osName = unmanagedInstance.getOperatingSystem();
                    GuestOS guestOS = null;
                    if (StringUtils.isNotEmpty(osName)) {
                        guestOS = guestOSDao.listByDisplayName(osName);
                    }
                    GuestOSHypervisor guestOSHypervisor = null;
                    if (guestOS != null) {
                        guestOSHypervisor = guestOSHypervisorDao.findByOsIdAndHypervisor(guestOS.getId(), host.getHypervisorType().toString(), host.getHypervisorVersion());
                    }
                    if (guestOSHypervisor == null && StringUtils.isNotEmpty(unmanagedInstance.getOperatingSystemId())) {
                        guestOSHypervisor = guestOSHypervisorDao.findByOsNameAndHypervisor(unmanagedInstance.getOperatingSystemId(), host.getHypervisorType().toString(), host.getHypervisorVersion());
                    }
                    if (guestOSHypervisor == null) {
                        if (guestOS != null) {
                            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Unable to find hypervisor guest OS ID: %s details for unmanaged VM: %s for hypervisor: %s version: %s. templateid parameter can be used to assign template for VM", guestOS.getUuid(), name, host.getHypervisorType().toString(), host.getHypervisorVersion()));
                        }
                        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Unable to retrieve guest OS details for unmanaged VM: %s with OS name: %s, OS ID: %s for hypervisor: %s version: %s. templateid parameter can be used to assign template for VM", name, osName, unmanagedInstance.getOperatingSystemId(), host.getHypervisorType().toString(), host.getHypervisorVersion()));
                    }
                    template.setGuestOSId(guestOSHypervisor.getGuestOsId());
                }
                userVm = importVirtualMachineInternal(unmanagedInstance, instanceName, zone, cluster, host, template, displayName, hostName, caller, owner, userId, serviceOffering, dataDiskOfferingMap, nicNetworkMap, nicIpAddressMap, details, cmd.getMigrateAllowed(), forced);
                break;
            }
        }
        if (userVm != null) {
            break;
        }
    }
    if (userVm == null) {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to find unmanaged vm with name: %s in cluster: %s", instanceName, cluster.getUuid()));
    }
    return responseGenerator.createUserVmResponse(ResponseObject.ResponseView.Full, "virtualmachine", userVm).get(0);
}
Also used : Account(com.cloud.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) ArrayList(java.util.ArrayList) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) GetUnmanagedInstancesCommand(com.cloud.agent.api.GetUnmanagedInstancesCommand) UserVm(com.cloud.uservm.UserVm) ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) GetUnmanagedInstancesAnswer(com.cloud.agent.api.GetUnmanagedInstancesAnswer) GuestOS(com.cloud.storage.GuestOS) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) Cluster(com.cloud.org.Cluster) VMInstanceVO(com.cloud.vm.VMInstanceVO) HostVO(com.cloud.host.HostVO) Answer(com.cloud.agent.api.Answer) GetUnmanagedInstancesAnswer(com.cloud.agent.api.GetUnmanagedInstancesAnswer) PrepareUnmanageVMInstanceAnswer(com.cloud.agent.api.PrepareUnmanageVMInstanceAnswer) GuestOSHypervisor(com.cloud.storage.GuestOSHypervisor) DataCenter(com.cloud.dc.DataCenter) UserVO(com.cloud.user.UserVO) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Aggregations

GuestOS (com.cloud.storage.GuestOS)26 ActionEvent (com.cloud.event.ActionEvent)8 DB (com.cloud.utils.db.DB)8 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)7 ArrayList (java.util.ArrayList)6 Account (com.cloud.user.Account)5 GuestOSResponse (com.cloud.api.response.GuestOSResponse)4 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)4 GuestOSVO (com.cloud.storage.GuestOSVO)4 VMTemplateVO (com.cloud.storage.VMTemplateVO)4 UserVO (com.cloud.user.UserVO)4 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)4 ServerApiException (org.apache.cloudstack.api.ServerApiException)4 ServerApiException (com.cloud.api.ServerApiException)3 DataCenter (com.cloud.dc.DataCenter)3 DataCenterVO (com.cloud.dc.DataCenterVO)3 ImageFormat (com.cloud.storage.Storage.ImageFormat)3 TemplateProfile (com.cloud.storage.TemplateProfile)3 ListResponse (com.cloud.api.response.ListResponse)2 HostVO (com.cloud.host.HostVO)2