Search in sources :

Example 6 with Host

use of com.cloud.host.Host in project cloudstack by apache.

the class RandomAllocator method allocateTo.

@Override
public List<Host> allocateTo(VirtualMachineProfile vmProfile, DeploymentPlan plan, Type type, ExcludeList avoid, int returnUpTo, boolean considerReservedCapacity) {
    long dcId = plan.getDataCenterId();
    Long podId = plan.getPodId();
    Long clusterId = plan.getClusterId();
    ServiceOffering offering = vmProfile.getServiceOffering();
    List<Host> suitableHosts = new ArrayList<Host>();
    if (type == Host.Type.Storage) {
        return suitableHosts;
    }
    String hostTag = offering.getHostTag();
    if (hostTag != null) {
        s_logger.debug("Looking for hosts in dc: " + dcId + "  pod:" + podId + "  cluster:" + clusterId + " having host tag:" + hostTag);
    } else {
        s_logger.debug("Looking for hosts in dc: " + dcId + "  pod:" + podId + "  cluster:" + clusterId);
    }
    // list all computing hosts, regardless of whether they support routing...it's random after all
    List<? extends Host> hosts = new ArrayList<HostVO>();
    if (hostTag != null) {
        hosts = _hostDao.listByHostTag(type, clusterId, podId, dcId, hostTag);
    } else {
        hosts = _resourceMgr.listAllUpAndEnabledHosts(type, clusterId, podId, dcId);
    }
    s_logger.debug("Random Allocator found " + hosts.size() + "  hosts");
    if (hosts.size() == 0) {
        return suitableHosts;
    }
    Collections.shuffle(hosts);
    for (Host host : hosts) {
        if (suitableHosts.size() == returnUpTo) {
            break;
        }
        if (!avoid.shouldAvoid(host)) {
            suitableHosts.add(host);
        } else {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Host name: " + host.getName() + ", hostId: " + host.getId() + " is in avoid set, skipping this and trying other available hosts");
            }
        }
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Random Host Allocator returning " + suitableHosts.size() + " suitable hosts");
    }
    return suitableHosts;
}
Also used : ServiceOffering(com.cloud.offering.ServiceOffering) ArrayList(java.util.ArrayList) Host(com.cloud.host.Host)

Example 7 with Host

use of com.cloud.host.Host in project cloudstack by apache.

the class NuageVspManagerImpl method addNuageVspDevice.

@Override
public NuageVspDeviceVO addNuageVspDevice(AddNuageVspDeviceCmd cmd) {
    final NuageVspResource resource = new NuageVspResource();
    final String deviceName = Network.Provider.NuageVsp.getName();
    ExternalNetworkDeviceManager.NetworkDevice networkDevice = ExternalNetworkDeviceManager.NetworkDevice.getNetworkDevice(deviceName);
    final Long physicalNetworkId = cmd.getPhysicalNetworkId();
    PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
    if (physicalNetwork == null) {
        throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
    }
    long zoneId = physicalNetwork.getDataCenterId();
    final PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder());
    if (ntwkSvcProvider == null) {
        throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device");
    } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
        throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device");
    }
    if (_nuageVspDao.listByPhysicalNetwork(physicalNetworkId).size() != 0) {
        throw new CloudRuntimeException("A NuageVsp device is already configured on this physical network");
    }
    // While the default VSD port is 8443, clustering via HAProxy will go over port 443 (CLOUD-58)
    int port = cmd.getPort() > 0 ? cmd.getPort() : 443;
    try {
        String apiVersion = null;
        String cmsUserPasswordBase64 = NuageVspUtil.encodePassword(cmd.getPassword());
        NuageVspResourceConfiguration resourceConfiguration = new NuageVspResourceConfiguration().guid(UUID.randomUUID().toString()).zoneId(String.valueOf(physicalNetwork.getDataCenterId())).hostName(cmd.getHostName()).cmsUser(cmd.getUserName()).cmsUserPassword(cmsUserPasswordBase64).port(String.valueOf(port)).apiVersion(NuageVspApiVersion.CURRENT.toString()).retryCount(NuageVspConstants.DEFAULT_API_RETRY_COUNT.toString()).retryInterval(NuageVspConstants.DEFAULT_API_RETRY_INTERVAL.toString()).apiRelativePath("/nuage");
        VspHost vspHost = resourceConfiguration.buildVspHost();
        NuageVspPluginClientLoader clientLoader = NuageVspPluginClientLoader.getClientLoader(vspHost);
        VspApiDefaults apiDefaults = clientLoader.getNuageVspManagerClient().getApiDefaults();
        if (StringUtils.isNotBlank(cmd.getApiVersion())) {
            if (!clientLoader.getNuageVspManagerClient().isSupportedApiVersion(cmd.getApiVersion())) {
                throw new CloudRuntimeException("Unsupported API version : " + cmd.getApiVersion());
            }
            apiVersion = cmd.getApiVersion();
        } else {
            boolean apiVersionFound = false;
            Map<NuageVspApiVersion, NuageVspApiVersion.Status> supportedVersions = clientLoader.getNuageVspManagerClient().getSupportedVersions();
            for (NuageVspApiVersion selectedVersion : supportedVersions.keySet()) {
                if (supportedVersions.get(selectedVersion) == NuageVspApiVersion.Status.CURRENT) {
                    apiVersion = selectedVersion.toString();
                    apiVersionFound = true;
                    break;
                }
            }
            if (!apiVersionFound) {
                throw new CloudRuntimeException("No supported API version found!");
            }
        }
        String retryCount = String.valueOf(MoreObjects.firstNonNull(cmd.getApiRetryCount(), apiDefaults.getRetryCount()));
        String retryInterval = String.valueOf(MoreObjects.firstNonNull(cmd.getApiRetryInterval(), apiDefaults.getRetryInterval()));
        resourceConfiguration.apiVersion(apiVersion).apiRelativePath("/nuage/api/" + apiVersion).retryCount(retryCount).retryInterval(retryInterval);
        Map<String, String> hostDetails = resourceConfiguration.build();
        resource.configure("Nuage VSD - " + cmd.getHostName(), Maps.<String, Object>newHashMap(hostDetails));
        Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, hostDetails);
        if (host == null) {
            throw new CloudRuntimeException("Failed to add Nuage Vsp Device due to internal error.");
        }
        NuageVspDeviceVO nuageVspDevice = new NuageVspDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName);
        _nuageVspDao.persist(nuageVspDevice);
        DetailVO detail = new DetailVO(host.getId(), "nuagevspdeviceid", String.valueOf(nuageVspDevice.getId()));
        _hostDetailsDao.persist(detail);
        NuageVspDeviceVO matchingNuageVspDevice = findMatchingNuageVspDevice(nuageVspDevice);
        String cmsId;
        if (matchingNuageVspDevice != null) {
            cmsId = findNuageVspCmsIdForDeviceOrHost(matchingNuageVspDevice.getId(), matchingNuageVspDevice.getHostId());
        } else {
            SyncNuageVspCmsIdCommand syncCmd = new SyncNuageVspCmsIdCommand(SyncType.REGISTER, null);
            SyncNuageVspCmsIdAnswer answer = (SyncNuageVspCmsIdAnswer) _agentMgr.easySend(nuageVspDevice.getHostId(), syncCmd);
            if (answer != null && answer.getSuccess()) {
                cmsId = answer.getNuageVspCmsId();
            } else {
                throw new CloudRuntimeException("Failed to register CMS ID");
            }
        }
        host = findNuageVspHost(nuageVspDevice.getHostId());
        registerNewNuageVspDevice(host.getId(), cmsId);
        resourceConfiguration.nuageVspCmsId(cmsId);
        resource.configure(cmd.getHostName(), Maps.<String, Object>newHashMap(resourceConfiguration.build()));
        if (matchingNuageVspDevice == null) {
            auditDomainsOnVsp((HostVO) host, true);
        }
        return nuageVspDevice;
    } catch (ConfigurationException e) {
        s_logger.error("Failed to configure Nuage VSD resource " + cmd.getHostName(), e);
        throw new CloudRuntimeException("Failed to configure Nuage VSD resource " + cmd.getHostName(), e);
    } catch (ExecutionException ee) {
        s_logger.error("Failed to add Nuage VSP device " + cmd.getHostName(), ee);
        throw new CloudRuntimeException("Failed to add Nuage VSP device " + cmd.getHostName(), ee);
    }
}
Also used : NuageVspResourceConfiguration(com.cloud.network.resource.NuageVspResourceConfiguration) VspApiDefaults(net.nuage.vsp.acs.client.api.model.VspApiDefaults) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NuageVspApiVersion(net.nuage.vsp.acs.client.common.NuageVspApiVersion) SyncNuageVspCmsIdAnswer(com.cloud.agent.api.sync.SyncNuageVspCmsIdAnswer) VspHost(net.nuage.vsp.acs.client.api.model.VspHost) ExecutionException(java.util.concurrent.ExecutionException) TransactionStatus(com.cloud.utils.db.TransactionStatus) Status(com.cloud.host.Status) NuageVspDeviceVO(com.cloud.network.NuageVspDeviceVO) ExternalNetworkDeviceManager(org.apache.cloudstack.network.ExternalNetworkDeviceManager) VspHost(net.nuage.vsp.acs.client.api.model.VspHost) Host(com.cloud.host.Host) NuageVspResource(com.cloud.network.resource.NuageVspResource) DetailVO(com.cloud.host.DetailVO) PhysicalNetworkServiceProviderVO(com.cloud.network.dao.PhysicalNetworkServiceProviderVO) SyncNuageVspCmsIdCommand(com.cloud.agent.api.sync.SyncNuageVspCmsIdCommand) NuageVspPluginClientLoader(net.nuage.vsp.acs.client.api.NuageVspPluginClientLoader)

Example 8 with Host

use of com.cloud.host.Host in project cloudstack by apache.

the class UserVmManagerImpl method startVirtualMachine.

@Override
public Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> startVirtualMachine(long vmId, Long hostId, Map<VirtualMachineProfile.Param, Object> additionalParams, String deploymentPlannerToUse) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    // Input validation
    Account callerAccount = CallContext.current().getCallingAccount();
    UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
    // if account is removed, return error
    if (callerAccount != null && callerAccount.getRemoved() != null) {
        throw new InvalidParameterValueException("The account " + callerAccount.getId() + " is removed");
    }
    UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
    }
    _accountMgr.checkAccess(callerAccount, null, true, vm);
    Account owner = _accountDao.findById(vm.getAccountId());
    if (owner == null) {
        throw new InvalidParameterValueException("The owner of " + vm + " does not exist: " + vm.getAccountId());
    }
    if (owner.getState() == Account.State.disabled) {
        throw new PermissionDeniedException("The owner of " + vm + " is disabled: " + vm.getAccountId());
    }
    Host destinationHost = null;
    if (hostId != null) {
        Account account = CallContext.current().getCallingAccount();
        if (!_accountService.isRootAdmin(account.getId())) {
            throw new PermissionDeniedException("Parameter hostid can only be specified by a Root Admin, permission denied");
        }
        destinationHost = _hostDao.findById(hostId);
        if (destinationHost == null) {
            throw new InvalidParameterValueException("Unable to find the host to deploy the VM, host id=" + hostId);
        }
    }
    // check if vm is security group enabled
    if (_securityGroupMgr.isVmSecurityGroupEnabled(vmId) && _securityGroupMgr.getSecurityGroupsForVm(vmId).isEmpty() && !_securityGroupMgr.isVmMappedToDefaultSecurityGroup(vmId) && _networkModel.canAddDefaultSecurityGroup()) {
        // if vm is not mapped to security group, create a mapping
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Vm " + vm + " is security group enabled, but not mapped to default security group; creating the mapping automatically");
        }
        SecurityGroup defaultSecurityGroup = _securityGroupMgr.getDefaultSecurityGroup(vm.getAccountId());
        if (defaultSecurityGroup != null) {
            List<Long> groupList = new ArrayList<Long>();
            groupList.add(defaultSecurityGroup.getId());
            _securityGroupMgr.addInstanceToGroups(vmId, groupList);
        }
    }
    DataCenterDeployment plan = null;
    if (destinationHost != null) {
        s_logger.debug("Destination Host to deploy the VM is specified, specifying a deployment plan to deploy the VM");
        plan = new DataCenterDeployment(vm.getDataCenterId(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null, null);
    }
    // Set parameters
    Map<VirtualMachineProfile.Param, Object> params = null;
    VMTemplateVO template = null;
    if (vm.isUpdateParameters()) {
        _vmDao.loadDetails(vm);
        // Check that the password was passed in and is valid
        template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId());
        String password = "saved_password";
        if (template.getEnablePassword()) {
            if (vm.getDetail("password") != null) {
                password = DBEncryptionUtil.decrypt(vm.getDetail("password"));
            } else {
                password = _mgr.generateRandomPassword();
            }
        }
        if (!validPassword(password)) {
            throw new InvalidParameterValueException("A valid password for this virtual machine was not provided.");
        }
        // Check if an SSH key pair was selected for the instance and if so
        // use it to encrypt & save the vm password
        encryptAndStorePassword(vm, password);
        params = new HashMap<VirtualMachineProfile.Param, Object>();
        if (additionalParams != null) {
            params.putAll(additionalParams);
        }
        params.put(VirtualMachineProfile.Param.VmPassword, password);
    }
    VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
    DeploymentPlanner planner = null;
    if (deploymentPlannerToUse != null) {
        // if set to null, the deployment planner would be later figured out either from global config var, or from
        // the service offering
        planner = _planningMgr.getDeploymentPlannerByName(deploymentPlannerToUse);
        if (planner == null) {
            throw new InvalidParameterValueException("Can't find a planner by name " + deploymentPlannerToUse);
        }
    }
    String reservationId = vmEntity.reserve(planner, plan, new ExcludeList(), Long.toString(callerUser.getId()));
    vmEntity.deploy(reservationId, Long.toString(callerUser.getId()), params);
    Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> vmParamPair = new Pair(vm, params);
    if (vm != null && vm.isUpdateParameters()) {
        // display purposes
        if (template.getEnablePassword()) {
            vm.setPassword((String) vmParamPair.second().get(VirtualMachineProfile.Param.VmPassword));
            vm.setUpdateParameters(false);
            if (vm.getDetail("password") != null) {
                _vmDetailsDao.remove(_vmDetailsDao.findDetail(vm.getId(), "password").getId());
            }
            _vmDao.update(vm.getId(), vm);
        }
    }
    return vmParamPair;
}
Also used : ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) Account(com.cloud.user.Account) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) VirtualMachineEntity(org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity) ArrayList(java.util.ArrayList) VMTemplateVO(com.cloud.storage.VMTemplateVO) Host(com.cloud.host.Host) SecurityGroup(com.cloud.network.security.SecurityGroup) UserVO(com.cloud.user.UserVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) DeploymentPlanner(com.cloud.deploy.DeploymentPlanner) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Pair(com.cloud.utils.Pair) SSHKeyPair(com.cloud.user.SSHKeyPair)

Example 9 with Host

use of com.cloud.host.Host in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method handleManagedStorage.

private void handleManagedStorage(final UserVmVO vm, final VolumeVO root) {
    if (Volume.State.Allocated.equals(root.getState())) {
        return;
    }
    final StoragePoolVO storagePool = _storagePoolDao.findById(root.getPoolId());
    if (storagePool != null && storagePool.isManaged()) {
        final Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId();
        if (hostId != null) {
            final VolumeInfo volumeInfo = volFactory.getVolume(root.getId());
            final Host host = _hostDao.findById(hostId);
            final Command cmd;
            if (host.getHypervisorType() == HypervisorType.XenServer) {
                final DiskTO disk = new DiskTO(volumeInfo.getTO(), root.getDeviceId(), root.getPath(), root.getVolumeType());
                // it's OK in this case to send a detach command to the host for a root volume as this
                // will simply lead to the SR that supports the root volume being removed
                cmd = new DettachCommand(disk, vm.getInstanceName());
                final DettachCommand detachCommand = (DettachCommand) cmd;
                detachCommand.setManaged(true);
                detachCommand.setStorageHost(storagePool.getHostAddress());
                detachCommand.setStoragePort(storagePool.getPort());
                detachCommand.set_iScsiName(root.get_iScsiName());
            } else {
                throw new CloudRuntimeException("This hypervisor type is not supported on managed storage for this command.");
            }
            final Commands cmds = new Commands(Command.OnError.Stop);
            cmds.addCommand(cmd);
            try {
                _agentMgr.send(hostId, cmds);
            } catch (final Exception ex) {
                throw new CloudRuntimeException(ex.getMessage());
            }
            if (!cmds.isSuccessful()) {
                for (final Answer answer : cmds.getAnswers()) {
                    if (!answer.getResult()) {
                        s_logger.warn("Failed to reset vm due to: " + answer.getDetails());
                        throw new CloudRuntimeException("Unable to reset " + vm + " due to " + answer.getDetails());
                    }
                }
            }
            // root.getPoolId() should be null if the VM we are detaching the disk from has never been started before
            final DataStore dataStore = root.getPoolId() != null ? _dataStoreMgr.getDataStore(root.getPoolId(), DataStoreRole.Primary) : null;
            volumeMgr.revokeAccess(volFactory.getVolume(root.getId()), host, dataStore);
        }
    }
}
Also used : GetVmStatsAnswer(com.cloud.agent.api.GetVmStatsAnswer) Answer(com.cloud.agent.api.Answer) StartAnswer(com.cloud.agent.api.StartAnswer) RestoreVMSnapshotAnswer(com.cloud.agent.api.RestoreVMSnapshotAnswer) GetVmDiskStatsAnswer(com.cloud.agent.api.GetVmDiskStatsAnswer) PvlanSetupCommand(com.cloud.agent.api.PvlanSetupCommand) DettachCommand(com.cloud.storage.command.DettachCommand) Command(com.cloud.agent.api.Command) GetVmStatsCommand(com.cloud.agent.api.GetVmStatsCommand) GetVmIpAddressCommand(com.cloud.agent.api.GetVmIpAddressCommand) GetVmDiskStatsCommand(com.cloud.agent.api.GetVmDiskStatsCommand) RestoreVMSnapshotCommand(com.cloud.agent.api.RestoreVMSnapshotCommand) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DataStore(com.cloud.engine.subsystem.api.storage.DataStore) StoragePoolVO(com.cloud.storage.datastore.db.StoragePoolVO) DettachCommand(com.cloud.storage.command.DettachCommand) Commands(com.cloud.agent.manager.Commands) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) Host(com.cloud.host.Host) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) CloudException(com.cloud.exception.CloudException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) DiskTO(com.cloud.agent.api.to.DiskTO)

Example 10 with Host

use of com.cloud.host.Host in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method startVirtualMachine.

@Override
public Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> startVirtualMachine(final long vmId, final Long hostId, final Map<VirtualMachineProfile.Param, Object> additionalParams, final String deploymentPlannerToUse) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    // Input validation
    final Account callerAccount = CallContext.current().getCallingAccount();
    final UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
    // if account is removed, return error
    if (callerAccount != null && callerAccount.getRemoved() != null) {
        throw new InvalidParameterValueException("The account " + callerAccount.getId() + " is removed");
    }
    final UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
    }
    _accountMgr.checkAccess(callerAccount, null, true, vm);
    final Account owner = _accountDao.findById(vm.getAccountId());
    if (owner == null) {
        throw new InvalidParameterValueException("The owner of " + vm + " does not exist: " + vm.getAccountId());
    }
    if (owner.getState() == Account.State.disabled) {
        throw new PermissionDeniedException("The owner of " + vm + " is disabled: " + vm.getAccountId());
    }
    Host destinationHost = null;
    if (hostId != null) {
        final Account account = CallContext.current().getCallingAccount();
        if (!_accountService.isRootAdmin(account.getId())) {
            throw new PermissionDeniedException("Parameter hostid can only be specified by a Root Admin, permission denied");
        }
        destinationHost = _hostDao.findById(hostId);
        if (destinationHost == null) {
            throw new InvalidParameterValueException("Unable to find the host to deploy the VM, host id=" + hostId);
        }
    }
    DataCenterDeployment plan = null;
    boolean deployOnGivenHost = false;
    if (destinationHost != null) {
        s_logger.debug("Destination Host to deploy the VM is specified, specifying a deployment plan to deploy the VM");
        plan = new DataCenterDeployment(vm.getDataCenterId(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null, null);
        deployOnGivenHost = true;
    }
    // Set parameters
    Map<VirtualMachineProfile.Param, Object> params = null;
    VMTemplateVO template = null;
    if (vm.isUpdateParameters()) {
        _vmDao.loadDetails(vm);
        // Check that the password was passed in and is valid
        template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId());
        String password = "saved_password";
        if (template.getEnablePassword()) {
            if (vm.getDetail("password") != null) {
                password = DBEncryptionUtil.decrypt(vm.getDetail("password"));
            } else {
                password = _mgr.generateRandomPassword();
            }
        }
        if (!validPassword(password)) {
            throw new InvalidParameterValueException("A valid password for this virtual machine was not provided.");
        }
        // Check if an SSH key pair was selected for the instance and if so
        // use it to encrypt & save the vm password
        encryptAndStorePassword(vm, password);
        params = new HashMap<>();
        if (additionalParams != null) {
            params.putAll(additionalParams);
        }
        params.put(VirtualMachineProfile.Param.VmPassword, password);
    }
    final VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
    DeploymentPlanner planner = null;
    if (deploymentPlannerToUse != null) {
        // if set to null, the deployment planner would be later figured out either from global config var, or from
        // the service offering
        planner = _planningMgr.getDeploymentPlannerByName(deploymentPlannerToUse);
        if (planner == null) {
            throw new InvalidParameterValueException("Can't find a planner by name " + deploymentPlannerToUse);
        }
    }
    final String reservationId = vmEntity.reserve(planner, plan, new ExcludeList(), Long.toString(callerUser.getId()));
    vmEntity.deploy(reservationId, Long.toString(callerUser.getId()), params, deployOnGivenHost);
    final Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> vmParamPair = new Pair(vm, params);
    if (vm != null && vm.isUpdateParameters()) {
        // display purposes
        if (template.getEnablePassword()) {
            vm.setPassword((String) vmParamPair.second().get(VirtualMachineProfile.Param.VmPassword));
            vm.setUpdateParameters(false);
            if (vm.getDetail("password") != null) {
                _vmDetailsDao.remove(_vmDetailsDao.findDetail(vm.getId(), "password").getId());
            }
            _vmDao.update(vm.getId(), vm);
        }
    }
    return vmParamPair;
}
Also used : ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) Account(com.cloud.user.Account) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) VirtualMachineEntity(com.cloud.engine.cloud.entity.api.VirtualMachineEntity) VMTemplateVO(com.cloud.storage.VMTemplateVO) Host(com.cloud.host.Host) UserVO(com.cloud.user.UserVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) DeploymentPlanner(com.cloud.deploy.DeploymentPlanner) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Pair(com.cloud.utils.Pair) SSHKeyPair(com.cloud.user.SSHKeyPair)

Aggregations

Host (com.cloud.host.Host)226 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)77 ArrayList (java.util.ArrayList)67 HashMap (java.util.HashMap)50 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)42 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)31 ServerApiException (org.apache.cloudstack.api.ServerApiException)30 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)28 Answer (com.cloud.agent.api.Answer)25 ConfigurationException (javax.naming.ConfigurationException)25 Pair (com.cloud.utils.Pair)24 Map (java.util.Map)24 StoragePool (com.cloud.storage.StoragePool)23 DeployDestination (com.cloud.deploy.DeployDestination)22 HostVO (com.cloud.host.HostVO)22 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)21 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)21 VolumeVO (com.cloud.storage.VolumeVO)21 NoTransitionException (com.cloud.utils.fsm.NoTransitionException)20 List (java.util.List)20