Search in sources :

Example 11 with Host

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

the class UserVmManagerImpl method migrateVirtualMachineWithVolume.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
public VirtualMachine migrateVirtualMachineWithVolume(final Long vmId, final Host destinationHost, final Map<String, String> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
    // Access check - only root administrator can migrate VM.
    final Account caller = CallContext.current().getCallingAccount();
    if (!_accountMgr.isRootAdmin(caller.getId())) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Caller is not a root admin, permission denied to migrate the VM");
        }
        throw new PermissionDeniedException("No permission to migrate VM, Only Root Admin can migrate a VM!");
    }
    final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("Unable to find the vm by id " + vmId);
    }
    if (vm.getState() != State.Running) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
        }
        final CloudRuntimeException ex = new CloudRuntimeException("VM is not Running, unable to migrate the vm with" + " specified id");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    if (serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
        throw new InvalidParameterValueException("Live Migration of GPU enabled VM is not supported");
    }
    if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.KVM)) {
        throw new InvalidParameterValueException("Unsupported hypervisor type for vm migration, we support" + " XenServer/KVM only");
    }
    final long srcHostId = vm.getHostId();
    final Host srcHost = _resourceMgr.getHost(srcHostId);
    if (srcHost == null) {
        throw new InvalidParameterValueException("Cannot migrate VM, there is not Host with id: " + srcHostId);
    }
    // Check if src and destination hosts are valid and migrating to same host
    if (destinationHost.getId() == srcHostId) {
        throw new InvalidParameterValueException("Cannot migrate VM, VM is already present on this host, please" + " specify valid destination host to migrate the VM");
    }
    // Check if the source and destination hosts are of the same type and support storage motion.
    if (!srcHost.getHypervisorType().equals(destinationHost.getHypervisorType())) {
        throw new CloudRuntimeException("The source and destination hosts are not of the same type " + "Source hypervisor type and version: " + srcHost.getHypervisorType().toString() + " " + srcHost.getHypervisorVersion() + ", Destination hypervisor type and version: " + destinationHost.getHypervisorType().toString() + " " + destinationHost.getHypervisorVersion());
    }
    if (srcHost.getHypervisorVersion() != null && !srcHost.getHypervisorVersion().equals(destinationHost.getHypervisorVersion())) {
        throw new CloudRuntimeException("The source and destination hosts are not of the same version. " + "Source hypervisor type and version: " + srcHost.getHypervisorType().toString() + " " + srcHost.getHypervisorVersion() + ", Destination hypervisor type and version: " + destinationHost.getHypervisorType().toString() + " " + destinationHost.getHypervisorVersion());
    }
    final HypervisorCapabilitiesVO capabilities = _hypervisorCapabilitiesDao.findByHypervisorTypeAndVersion(srcHost.getHypervisorType(), srcHost.getHypervisorVersion());
    if (!capabilities.isStorageMotionSupported()) {
        throw new CloudRuntimeException("Migration with storage isn't supported on hypervisor " + srcHost.getHypervisorType() + " of version " + srcHost.getHypervisorVersion());
    }
    // Check if destination host is up.
    if (destinationHost.getState() != com.cloud.host.Status.Up || destinationHost.getResourceState() != ResourceState.Enabled) {
        throw new CloudRuntimeException("Cannot migrate VM, destination host is not in correct state, has " + "status: " + destinationHost.getState() + ", state: " + destinationHost.getResourceState());
    }
    // Check that Vm does not have VM Snapshots
    if (_vmSnapshotDao.findByVm(vmId).size() > 0) {
        throw new InvalidParameterValueException("VM with VM Snapshots cannot be migrated with storage, please remove all VM snapshots");
    }
    final List<VolumeVO> vmVolumes = _volsDao.findUsableVolumesForInstance(vm.getId());
    final Map<Long, Long> volToPoolObjectMap = new HashMap<>();
    if (!isVMUsingLocalStorage(vm) && destinationHost.getClusterId().equals(srcHost.getClusterId())) {
        if (volumeToPool.isEmpty()) {
            // then fail the call. migrateVirtualMachine api should have been used.
            throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destinationHost + " doesn't involve migrating the volumes.");
        }
    }
    if (!volumeToPool.isEmpty()) {
        // Check if all the volumes and pools passed as parameters are valid.
        for (final Map.Entry<String, String> entry : volumeToPool.entrySet()) {
            final VolumeVO volume = _volsDao.findByUuid(entry.getKey());
            final StoragePoolVO pool = _storagePoolDao.findByUuid(entry.getValue());
            if (volume == null) {
                throw new InvalidParameterValueException("There is no volume present with the given id " + entry.getKey());
            } else if (pool == null) {
                throw new InvalidParameterValueException("There is no storage pool present with the given id " + entry.getValue());
            } else if (pool.isInMaintenance()) {
                throw new InvalidParameterValueException("Cannot migrate volume " + volume + "to the destination storage pool " + pool.getName() + " as the storage pool is in maintenance mode.");
            } else {
                // Verify the volume given belongs to the vm.
                if (!vmVolumes.contains(volume)) {
                    throw new InvalidParameterValueException("There volume " + volume + " doesn't belong to " + "the virtual machine " + vm + " that has to be migrated");
                }
                volToPoolObjectMap.put(volume.getId(), pool.getId());
            }
        }
    }
    // Check if all the volumes are in the correct state.
    for (final VolumeVO volume : vmVolumes) {
        if (volume.getState() != Volume.State.Ready) {
            throw new CloudRuntimeException("Volume " + volume + " of the VM is not in Ready state. Cannot " + "migrate the vm with its volumes.");
        }
    }
    // Check max guest vm limit for the destinationHost.
    final HostVO destinationHostVO = _hostDao.findById(destinationHost.getId());
    if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) {
        throw new VirtualMachineMigrationException("Host name: " + destinationHost.getName() + ", hostId: " + destinationHost.getId() + " already has max running vms (count includes system VMs). Cannot" + " migrate to this host");
    }
    checkHostsDedication(vm, srcHostId, destinationHost.getId());
    _itMgr.migrateWithStorage(vm.getUuid(), srcHostId, destinationHost.getId(), volToPoolObjectMap);
    return _vmDao.findById(vm.getId());
}
Also used : HypervisorCapabilitiesVO(com.cloud.hypervisor.HypervisorCapabilitiesVO) Account(com.cloud.user.Account) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Host(com.cloud.host.Host) HostVO(com.cloud.host.HostVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StoragePoolVO(com.cloud.storage.datastore.db.StoragePoolVO) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ActionEvent(com.cloud.event.ActionEvent)

Example 12 with Host

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

the class UserVmManagerImpl method setupVmForPvlan.

@Override
public boolean setupVmForPvlan(final boolean add, final Long hostId, final NicProfile nic) {
    if (!nic.getBroadCastUri().getScheme().equals("pvlan")) {
        return false;
    }
    String op = "add";
    if (!add) {
        op = "delete";
    }
    final Network network = _networkDao.findById(nic.getNetworkId());
    final Host host = _hostDao.findById(hostId);
    final String networkTag = _networkModel.getNetworkTag(host.getHypervisorType(), network);
    final PvlanSetupCommand cmd = PvlanSetupCommand.createVmSetup(op, nic.getBroadCastUri(), networkTag, nic.getMacAddress());
    final Answer answer;
    try {
        answer = _agentMgr.send(hostId, cmd);
    } catch (final OperationTimedoutException e) {
        s_logger.warn("Timed Out", e);
        return false;
    } catch (final AgentUnavailableException e) {
        s_logger.warn("Agent Unavailable ", e);
        return false;
    }
    boolean result = true;
    if (answer == null || !answer.getResult()) {
        result = false;
    }
    return result;
}
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) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Host(com.cloud.host.Host) PvlanSetupCommand(com.cloud.agent.api.PvlanSetupCommand)

Example 13 with Host

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

the class RandomAllocator method findSuitableHosts.

private List<Host> findSuitableHosts(VirtualMachineProfile vmProfile, DeploymentPlan plan, Type type, ExcludeList avoid, List<? extends Host> hosts, int returnUpTo, boolean considerReservedCapacity) {
    long dcId = plan.getDataCenterId();
    Long podId = plan.getPodId();
    Long clusterId = plan.getClusterId();
    ServiceOffering offering = vmProfile.getServiceOffering();
    List<? extends Host> hostsCopy = null;
    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);
    }
    if (hosts != null) {
        // retain all computing hosts, regardless of whether they support routing...it's random after all
        hostsCopy = new ArrayList<Host>(hosts);
        if (hostTag != null) {
            hostsCopy.retainAll(_hostDao.listByHostTag(type, clusterId, podId, dcId, hostTag));
        } else {
            hostsCopy.retainAll(_resourceMgr.listAllUpAndEnabledHosts(type, clusterId, podId, dcId));
        }
    } else {
        // list all computing hosts, regardless of whether they support routing...it's random after all
        hostsCopy = new ArrayList<HostVO>();
        if (hostTag != null) {
            hostsCopy = _hostDao.listByHostTag(type, clusterId, podId, dcId, hostTag);
        } else {
            hostsCopy = _resourceMgr.listAllUpAndEnabledHosts(type, clusterId, podId, dcId);
        }
    }
    s_logger.debug("Random Allocator found " + hostsCopy.size() + "  hosts");
    if (hostsCopy.size() == 0) {
        return suitableHosts;
    }
    Collections.shuffle(hostsCopy);
    for (Host host : hostsCopy) {
        if (suitableHosts.size() == returnUpTo) {
            break;
        }
        if (avoid.shouldAvoid(host)) {
            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");
            }
            continue;
        }
        Pair<Boolean, Boolean> cpuCapabilityAndCapacity = capacityManager.checkIfHostHasCpuCapabilityAndCapacity(host, offering, considerReservedCapacity);
        if (!cpuCapabilityAndCapacity.first() || !cpuCapabilityAndCapacity.second()) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Not using host " + host.getId() + "; host has cpu capability? " + cpuCapabilityAndCapacity.first() + ", host has capacity?" + cpuCapabilityAndCapacity.second());
            }
            continue;
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Found a suitable host, adding to list: " + host.getId());
        }
        suitableHosts.add(host);
    }
    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) HostVO(com.cloud.host.HostVO)

Example 14 with Host

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

the class JuniperSRXExternalFirewallElement method listExternalFirewalls.

@Override
@Deprecated
public List<Host> listExternalFirewalls(ListExternalFirewallsCmd cmd) {
    List<Host> firewallHosts = new ArrayList<Host>();
    Long zoneId = cmd.getZoneId();
    DataCenterVO zone = null;
    PhysicalNetworkVO pNetwork = null;
    if (zoneId != null) {
        zone = _dcDao.findById(zoneId);
        if (zone == null) {
            throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId);
        }
        List<PhysicalNetworkVO> physicalNetworks = _physicalNetworkDao.listByZone(zoneId);
        if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) {
            throw new InvalidParameterValueException("There are no physical networks or multiple physical networks configured in zone with ID: " + zoneId + " to add this device.");
        }
        pNetwork = physicalNetworks.get(0);
    }
    firewallHosts.addAll(listExternalFirewalls(pNetwork.getId(), NetworkDevice.JuniperSRXFirewall.getName()));
    return firewallHosts;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ArrayList(java.util.ArrayList) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) Host(com.cloud.host.Host)

Example 15 with Host

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

the class AddExternalFirewallCmd method execute.

@SuppressWarnings("deprecation")
@Override
public void execute() {
    try {
        Host externalFirewall = _srxElementService.addExternalFirewall(this);
        ExternalFirewallResponse response = _srxElementService.createExternalFirewallResponse(externalFirewall);
        response.setObjectName("externalfirewall");
        response.setResponseName(getCommandName());
        this.setResponseObject(response);
    } catch (InvalidParameterValueException ipve) {
        throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage());
    } catch (CloudRuntimeException cre) {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, cre.getMessage());
    }
}
Also used : ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Host(com.cloud.host.Host) ExternalFirewallResponse(org.apache.cloudstack.api.response.ExternalFirewallResponse)

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