Search in sources :

Example 31 with HypervisorType

use of com.cloud.hypervisor.Hypervisor.HypervisorType in project cloudstack by apache.

the class UserVmManagerImpl method vmStorageMigration.

@Override
public VirtualMachine vmStorageMigration(Long vmId, StoragePool destPool) {
    // access check - only root admin can migrate VM
    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!");
    }
    VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("Unable to find the VM by id=" + vmId);
    }
    if (vm.getState() != State.Stopped) {
        InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Stopped, unable to migrate the vm having the specified id");
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    if (vm.getType() != VirtualMachine.Type.User) {
        throw new InvalidParameterValueException("can only do storage migration on user vm");
    }
    List<VolumeVO> vols = _volsDao.findByInstance(vm.getId());
    if (vols.size() > 1) {
        throw new InvalidParameterValueException("Data disks attached to the vm, can not migrate. Need to dettach data disks at first");
    }
    // Check that Vm does not have VM Snapshots
    if (_vmSnapshotDao.findByVm(vmId).size() > 0) {
        throw new InvalidParameterValueException("VM's disk cannot be migrated, please remove all the VM Snapshots for this VM");
    }
    HypervisorType destHypervisorType = destPool.getHypervisor();
    if (destHypervisorType == null) {
        destHypervisorType = _clusterDao.findById(destPool.getClusterId()).getHypervisorType();
    }
    if (vm.getHypervisorType() != destHypervisorType) {
        throw new InvalidParameterValueException("hypervisor is not compatible: dest: " + destHypervisorType.toString() + ", vm: " + vm.getHypervisorType().toString());
    }
    _itMgr.storageMigration(vm.getUuid(), destPool);
    return _vmDao.findById(vm.getId());
}
Also used : HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) Account(com.cloud.user.Account) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 32 with HypervisorType

use of com.cloud.hypervisor.Hypervisor.HypervisorType in project cloudstack by apache.

the class UserVmManagerImpl method createAdvancedVirtualMachine.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_CREATE, eventDescription = "deploying Vm", create = true)
public UserVm createAdvancedVirtualMachine(DataCenter zone, ServiceOffering serviceOffering, VirtualMachineTemplate template, List<Long> networkIdList, Account owner, String hostName, String displayName, Long diskOfferingId, Long diskSize, String group, HypervisorType hypervisor, HTTPMethod httpmethod, String userData, String sshKeyPair, Map<Long, IpAddresses> requestedIps, IpAddresses defaultIps, Boolean displayvm, String keyboard, List<Long> affinityGroupIdList, Map<String, String> customParametrs, String customId) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, StorageUnavailableException, ResourceAllocationException {
    Account caller = CallContext.current().getCallingAccount();
    List<NetworkVO> networkList = new ArrayList<NetworkVO>();
    // Verify that caller can perform actions in behalf of vm owner
    _accountMgr.checkAccess(caller, null, true, owner);
    // Verify that owner can use the service offering
    _accountMgr.checkAccess(owner, serviceOffering);
    _accountMgr.checkAccess(owner, _diskOfferingDao.findById(diskOfferingId));
    List<HypervisorType> vpcSupportedHTypes = _vpcMgr.getSupportedVpcHypervisors();
    if (networkIdList == null || networkIdList.isEmpty()) {
        NetworkVO defaultNetwork = null;
        // if no network is passed in
        // Check if default virtual network offering has
        // Availability=Required. If it's true, search for corresponding
        // network
        // * if network is found, use it. If more than 1 virtual network is
        // found, throw an error
        // * if network is not found, create a new one and use it
        List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false);
        if (requiredOfferings.size() < 1) {
            throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + " to automatically create the network as a part of vm creation");
        }
        if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) {
            // get Virtual networks
            List<? extends Network> virtualNetworks = _networkModel.listNetworksForAccount(owner.getId(), zone.getId(), Network.GuestType.Isolated);
            if (virtualNetworks == null) {
                throw new InvalidParameterValueException("No (virtual) networks are found for account " + owner);
            }
            if (virtualNetworks.isEmpty()) {
                long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType());
                // Validate physical network
                PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
                if (physicalNetwork == null) {
                    throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + requiredOfferings.get(0).getTags());
                }
                s_logger.debug("Creating network for account " + owner + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of deployVM process");
                Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network", owner.getAccountName() + "-network", null, null, null, null, owner, null, physicalNetwork, zone.getId(), ACLType.Account, null, null, null, null, true, null);
                if (newNetwork != null) {
                    defaultNetwork = _networkDao.findById(newNetwork.getId());
                }
            } else if (virtualNetworks.size() > 1) {
                throw new InvalidParameterValueException("More than 1 default Isolated networks are found for account " + owner + "; please specify networkIds");
            } else {
                defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId());
            }
        } else {
            throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled);
        }
        if (defaultNetwork != null) {
            networkList.add(defaultNetwork);
        }
    } else {
        for (Long networkId : networkIdList) {
            NetworkVO network = _networkDao.findById(networkId);
            if (network == null) {
                throw new InvalidParameterValueException("Unable to find network by id " + networkIdList.get(0).longValue());
            }
            if (network.getVpcId() != null) {
                // supported for vpc networks
                if (template.getFormat() != ImageFormat.ISO && !vpcSupportedHTypes.contains(template.getHypervisorType())) {
                    throw new InvalidParameterValueException("Can't create vm from template with hypervisor " + template.getHypervisorType() + " in vpc network " + network);
                } else if (template.getFormat() == ImageFormat.ISO && !vpcSupportedHTypes.contains(hypervisor)) {
                    // for vpc networks
                    throw new InvalidParameterValueException("Can't create vm of hypervisor type " + hypervisor + " in vpc network");
                }
            }
            _networkModel.checkNetworkPermissions(owner, network);
            // don't allow to use system networks
            NetworkOffering networkOffering = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
            if (networkOffering.isSystemOnly()) {
                throw new InvalidParameterValueException("Network id=" + networkId + " is system only and can't be used for vm deployment");
            }
            networkList.add(network);
        }
    }
    return createVirtualMachine(zone, serviceOffering, template, hostName, displayName, owner, diskOfferingId, diskSize, networkList, null, group, httpmethod, userData, sshKeyPair, hypervisor, caller, requestedIps, defaultIps, displayvm, keyboard, affinityGroupIdList, customParametrs, customId);
}
Also used : Account(com.cloud.user.Account) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkOffering(com.cloud.offering.NetworkOffering) ArrayList(java.util.ArrayList) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) ActionEvent(com.cloud.event.ActionEvent)

Example 33 with HypervisorType

use of com.cloud.hypervisor.Hypervisor.HypervisorType in project cloudstack by apache.

the class CloudStackPrimaryDataStoreLifeCycleImpl method deleteDataStore.

@DB
@Override
public boolean deleteDataStore(DataStore store) {
    List<StoragePoolHostVO> hostPoolRecords = _storagePoolHostDao.listByPoolId(store.getId());
    StoragePool pool = (StoragePool) store;
    boolean deleteFlag = false;
    // find the hypervisor where the storage is attached to.
    HypervisorType hType = null;
    if (hostPoolRecords.size() > 0) {
        hType = getHypervisorType(hostPoolRecords.get(0).getHostId());
    }
    // Remove the SR associated with the Xenserver
    for (StoragePoolHostVO host : hostPoolRecords) {
        DeleteStoragePoolCommand deleteCmd = new DeleteStoragePoolCommand(pool);
        final Answer answer = agentMgr.easySend(host.getHostId(), deleteCmd);
        if (answer != null && answer.getResult()) {
            deleteFlag = true;
            // if host is KVM hypervisor then send deleteStoragepoolcmd to all the kvm hosts.
            if (HypervisorType.KVM != hType) {
                break;
            }
        } else {
            if (answer != null) {
                s_logger.debug("Failed to delete storage pool: " + answer.getResult());
            }
        }
    }
    if (!hostPoolRecords.isEmpty() && !deleteFlag) {
        throw new CloudRuntimeException("Failed to delete storage pool on host");
    }
    return dataStoreHelper.deletePrimaryDataStore(store);
}
Also used : HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) Answer(com.cloud.agent.api.Answer) StoragePool(com.cloud.storage.StoragePool) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DeleteStoragePoolCommand(com.cloud.agent.api.DeleteStoragePoolCommand) DB(com.cloud.utils.db.DB)

Example 34 with HypervisorType

use of com.cloud.hypervisor.Hypervisor.HypervisorType in project cloudstack by apache.

the class ElastistorPrimaryDataStoreLifeCycle method deleteDataStore.

@SuppressWarnings("finally")
@Override
public boolean deleteDataStore(DataStore store) {
    List<StoragePoolHostVO> hostPoolRecords = _storagePoolHostDao.listByPoolId(store.getId());
    StoragePool pool = (StoragePool) store;
    // find the hypervisor where the storage is attached to.
    HypervisorType hType = null;
    if (hostPoolRecords.size() > 0) {
        hType = getHypervisorType(hostPoolRecords.get(0).getHostId());
    }
    StoragePoolVO storagePoolVO = _storagePoolDao.findById(store.getId());
    if (!(storagePoolVO.isManaged())) {
        // Remove the SR associated with the Xenserver
        for (StoragePoolHostVO host : hostPoolRecords) {
            DeleteStoragePoolCommand deleteCmd = new DeleteStoragePoolCommand(pool);
            final Answer answer = agentMgr.easySend(host.getHostId(), deleteCmd);
            if (answer != null && answer.getResult()) {
                // to all the kvm hosts.
                if (HypervisorType.KVM != hType) {
                    break;
                }
            } else {
                if (answer != null) {
                    s_logger.error("Failed to delete storage pool: " + answer.getResult());
                }
            }
        }
    }
    // delete the Elastistor volume at backend
    deleteElastistorVolume(pool, storagePoolVO.isManaged());
    return _dataStoreHelper.deletePrimaryDataStore(store);
}
Also used : HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) Answer(com.cloud.agent.api.Answer) StoragePool(com.cloud.storage.StoragePool) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) DeleteStoragePoolCommand(com.cloud.agent.api.DeleteStoragePoolCommand)

Example 35 with HypervisorType

use of com.cloud.hypervisor.Hypervisor.HypervisorType in project cloudstack by apache.

the class CloudZonesStartupProcessor method updateComputeHost.

protected void updateComputeHost(final HostVO host, final StartupCommand startup, final Host.Type type) throws AgentAuthnException {
    String zoneToken = startup.getDataCenter();
    if (zoneToken == null) {
        s_logger.warn("No Zone Token passed in, cannot not find zone for the agent");
        throw new AgentAuthnException("No Zone Token passed in, cannot not find zone for agent");
    }
    DataCenterVO zone = _zoneDao.findByToken(zoneToken);
    if (zone == null) {
        zone = _zoneDao.findByName(zoneToken);
        if (zone == null) {
            try {
                long zoneId = Long.parseLong(zoneToken);
                zone = _zoneDao.findById(zoneId);
                if (zone == null) {
                    throw new AgentAuthnException("Could not find zone for agent with token " + zoneToken);
                }
            } catch (NumberFormatException nfe) {
                throw new AgentAuthnException("Could not find zone for agent with token " + zoneToken);
            }
        }
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Successfully loaded the DataCenter from the zone token passed in ");
    }
    long zoneId = zone.getId();
    ResourceDetail maxHostsInZone = _zoneDetailsDao.findDetail(zoneId, ZoneConfig.MaxHosts.key());
    if (maxHostsInZone != null) {
        long maxHosts = Long.parseLong(maxHostsInZone.getValue());
        long currentCountOfHosts = _hostDao.countRoutingHostsByDataCenter(zoneId);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Number of hosts in Zone:" + currentCountOfHosts + ", max hosts limit: " + maxHosts);
        }
        if (currentCountOfHosts >= maxHosts) {
            throw new AgentAuthnException("Number of running Routing hosts in the Zone:" + zone.getName() + " is already at the max limit:" + maxHosts + ", cannot start one more host");
        }
    }
    HostPodVO pod = null;
    if (startup.getPrivateIpAddress() == null) {
        s_logger.warn("No private IP address passed in for the agent, cannot not find pod for agent");
        throw new AgentAuthnException("No private IP address passed in for the agent, cannot not find pod for agent");
    }
    if (startup.getPrivateNetmask() == null) {
        s_logger.warn("No netmask passed in for the agent, cannot not find pod for agent");
        throw new AgentAuthnException("No netmask passed in for the agent, cannot not find pod for agent");
    }
    if (host.getPodId() != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Pod is already created for this agent, looks like agent is reconnecting...");
        }
        pod = _podDao.findById(host.getPodId());
        if (!checkCIDR(type, pod, startup.getPrivateIpAddress(), startup.getPrivateNetmask())) {
            pod = null;
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Subnet of Pod does not match the subnet of the agent, not using this Pod: " + host.getPodId());
            }
        } else {
            updatePodNetmaskIfNeeded(pod, startup.getPrivateNetmask());
        }
    }
    if (pod == null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Trying to detect the Pod to use from the agent's ip address and netmask passed in ");
        }
        //deduce pod
        boolean podFound = false;
        List<HostPodVO> podsInZone = _podDao.listByDataCenterId(zoneId);
        for (HostPodVO hostPod : podsInZone) {
            if (checkCIDR(type, hostPod, startup.getPrivateIpAddress(), startup.getPrivateNetmask())) {
                pod = hostPod;
                //found the default POD having the same subnet.
                updatePodNetmaskIfNeeded(pod, startup.getPrivateNetmask());
                podFound = true;
                break;
            }
        }
        if (!podFound) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Creating a new Pod since no default Pod found that matches the agent's ip address and netmask passed in ");
            }
            if (startup.getGatewayIpAddress() == null) {
                s_logger.warn("No Gateway IP address passed in for the agent, cannot create a new pod for the agent");
                throw new AgentAuthnException("No Gateway IP address passed in for the agent, cannot create a new pod for the agent");
            }
            //auto-create a new pod, since pod matching the agent's ip is not found
            String podName = "POD-" + (podsInZone.size() + 1);
            try {
                String gateway = startup.getGatewayIpAddress();
                String cidr = NetUtils.getCidrFromGatewayAndNetmask(gateway, startup.getPrivateNetmask());
                String[] cidrPair = cidr.split("\\/");
                String cidrAddress = cidrPair[0];
                long cidrSize = Long.parseLong(cidrPair[1]);
                String startIp = NetUtils.getIpRangeStartIpFromCidr(cidrAddress, cidrSize);
                String endIp = NetUtils.getIpRangeEndIpFromCidr(cidrAddress, cidrSize);
                pod = _configurationManager.createPod(-1, podName, zoneId, gateway, cidr, startIp, endIp, null, true);
            } catch (Exception e) {
                // no longer tolerate exception during the cluster creation phase
                throw new CloudRuntimeException("Unable to create new Pod " + podName + " in Zone: " + zoneId, e);
            }
        }
    }
    final StartupRoutingCommand scc = (StartupRoutingCommand) startup;
    ClusterVO cluster = null;
    if (host.getClusterId() != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Cluster is already created for this agent, looks like agent is reconnecting...");
        }
        cluster = _clusterDao.findById(host.getClusterId());
    }
    if (cluster == null) {
        //auto-create cluster - assume one host per cluster
        String clusterName = "Cluster-" + startup.getPrivateIpAddress();
        ClusterVO existingCluster = _clusterDao.findBy(clusterName, pod.getId());
        if (existingCluster != null) {
            cluster = existingCluster;
        } else {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Creating a new Cluster for this agent with name: " + clusterName + " in Pod: " + pod.getId() + ", in Zone:" + zoneId);
            }
            cluster = new ClusterVO(zoneId, pod.getId(), clusterName);
            cluster.setHypervisorType(scc.getHypervisorType().toString());
            try {
                cluster = _clusterDao.persist(cluster);
            } catch (Exception e) {
                // no longer tolerate exception during the cluster creation phase
                throw new CloudRuntimeException("Unable to create cluster " + clusterName + " in pod " + pod.getId() + " and data center " + zoneId, e);
            }
        }
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Detected Zone: " + zoneId + ", Pod: " + pod.getId() + ", Cluster:" + cluster.getId());
    }
    host.setDataCenterId(zone.getId());
    host.setPodId(pod.getId());
    host.setClusterId(cluster.getId());
    host.setPrivateIpAddress(startup.getPrivateIpAddress());
    host.setPrivateNetmask(startup.getPrivateNetmask());
    host.setPrivateMacAddress(startup.getPrivateMacAddress());
    host.setPublicIpAddress(startup.getPublicIpAddress());
    host.setPublicMacAddress(startup.getPublicMacAddress());
    host.setPublicNetmask(startup.getPublicNetmask());
    host.setStorageIpAddress(startup.getStorageIpAddress());
    host.setStorageMacAddress(startup.getStorageMacAddress());
    host.setStorageNetmask(startup.getStorageNetmask());
    host.setVersion(startup.getVersion());
    host.setName(startup.getName());
    host.setType(type);
    host.setStorageUrl(startup.getIqn());
    host.setLastPinged(System.currentTimeMillis() >> 10);
    host.setCaps(scc.getCapabilities());
    host.setCpus(scc.getCpus());
    host.setTotalMemory(scc.getMemory());
    host.setSpeed(scc.getSpeed());
    HypervisorType hyType = scc.getHypervisorType();
    host.setHypervisorType(hyType);
    host.setHypervisorVersion(scc.getHypervisorVersion());
    updateHostDetails(host, scc);
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) ClusterVO(com.cloud.dc.ClusterVO) ResourceDetail(org.apache.cloudstack.api.ResourceDetail) HostPodVO(com.cloud.dc.HostPodVO) ConfigurationException(javax.naming.ConfigurationException) ConnectionException(com.cloud.exception.ConnectionException) AgentAuthnException(com.cloud.agent.manager.authn.AgentAuthnException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) AgentAuthnException(com.cloud.agent.manager.authn.AgentAuthnException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StartupRoutingCommand(com.cloud.agent.api.StartupRoutingCommand)

Aggregations

HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)57 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)25 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)20 ArrayList (java.util.ArrayList)19 Account (com.cloud.user.Account)15 VMTemplateVO (com.cloud.storage.VMTemplateVO)12 ClusterVO (com.cloud.dc.ClusterVO)10 HostVO (com.cloud.host.HostVO)8 UserVmVO (com.cloud.vm.UserVmVO)8 HashMap (java.util.HashMap)8 StoragePoolVO (org.apache.cloudstack.storage.datastore.db.StoragePoolVO)8 DataCenterVO (com.cloud.dc.DataCenterVO)7 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)7 DataStore (org.apache.cloudstack.engine.subsystem.api.storage.DataStore)7 Answer (com.cloud.agent.api.Answer)6 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)6 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)6 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)6 ServiceOfferingVO (com.cloud.service.ServiceOfferingVO)6 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)5