Search in sources :

Example 46 with Host

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

the class BaremetalDhcpManagerImpl method addDchpServer.

@Override
@DB
public BaremetalDhcpVO addDchpServer(AddBaremetalDhcpCmd cmd) {
    PhysicalNetworkVO pNetwork = null;
    long zoneId;
    if (cmd.getPhysicalNetworkId() == null || cmd.getUrl() == null || cmd.getUsername() == null || cmd.getPassword() == null) {
        throw new IllegalArgumentException("At least one of the required parameters(physical network id, url, username, password) is null");
    }
    pNetwork = _physicalNetworkDao.findById(cmd.getPhysicalNetworkId());
    if (pNetwork == null) {
        throw new IllegalArgumentException("Could not find phyical network with ID: " + cmd.getPhysicalNetworkId());
    }
    zoneId = pNetwork.getDataCenterId();
    DataCenterVO zone = _dcDao.findById(zoneId);
    PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), BaremetalDhcpManager.BAREMETAL_DHCP_SERVICE_PROVIDER.getName());
    if (ntwkSvcProvider == null) {
        throw new CloudRuntimeException("Network Service Provider: " + BaremetalDhcpManager.BAREMETAL_DHCP_SERVICE_PROVIDER.getName() + " is not enabled in the physical network: " + cmd.getPhysicalNetworkId() + "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: " + cmd.getPhysicalNetworkId() + "to add this device");
    }
    List<HostVO> dhcps = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.BaremetalDhcp, null, null, zoneId);
    if (dhcps.size() != 0) {
        throw new IllegalArgumentException("Already had a DHCP server in zone: " + zoneId);
    }
    URI uri;
    try {
        uri = new URI(cmd.getUrl());
    } catch (Exception e) {
        s_logger.debug(e);
        throw new IllegalArgumentException(e.getMessage());
    }
    String ipAddress = uri.getHost();
    if (ipAddress == null) {
        // the url is raw ip. For backforward compatibility, we have to support http://ip format as well
        ipAddress = cmd.getUrl();
    }
    String guid = getDhcpServerGuid(Long.toString(zoneId), "ExternalDhcp", ipAddress);
    Map params = new HashMap<String, String>();
    params.put("type", cmd.getDhcpType());
    params.put("zone", Long.toString(zoneId));
    params.put("ip", ipAddress);
    params.put("username", cmd.getUsername());
    params.put("password", cmd.getPassword());
    params.put("guid", guid);
    String dns = zone.getDns1();
    if (dns == null) {
        dns = zone.getDns2();
    }
    params.put("dns", dns);
    ServerResource resource = null;
    try {
        if (cmd.getDhcpType().equalsIgnoreCase(BaremetalDhcpType.DNSMASQ.toString())) {
            resource = new BaremetalDnsmasqResource();
            resource.configure("Dnsmasq resource", params);
        } else if (cmd.getDhcpType().equalsIgnoreCase(BaremetalDhcpType.DHCPD.toString())) {
            resource = new BaremetalDhcpdResource();
            resource.configure("Dhcpd resource", params);
        } else {
            throw new CloudRuntimeException("Unsupport DHCP server type: " + cmd.getDhcpType());
        }
    } catch (Exception e) {
        s_logger.debug(e);
        throw new CloudRuntimeException(e.getMessage());
    }
    Host dhcpServer = _resourceMgr.addHost(zoneId, resource, Host.Type.BaremetalDhcp, params);
    if (dhcpServer == null) {
        throw new CloudRuntimeException("Cannot add external Dhcp server as a host");
    }
    BaremetalDhcpVO vo = new BaremetalDhcpVO();
    vo.setDeviceType(cmd.getDhcpType());
    vo.setHostId(dhcpServer.getId());
    vo.setNetworkServiceProviderId(ntwkSvcProvider.getId());
    vo.setPhysicalNetworkId(cmd.getPhysicalNetworkId());
    _extDhcpDao.persist(vo);
    return vo;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) HashMap(java.util.HashMap) ServerResource(com.cloud.resource.ServerResource) Host(com.cloud.host.Host) URI(java.net.URI) HostVO(com.cloud.host.HostVO) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UnableDeleteHostException(com.cloud.resource.UnableDeleteHostException) BaremetalDhcpVO(com.cloud.baremetal.database.BaremetalDhcpVO) PhysicalNetworkServiceProviderVO(com.cloud.network.dao.PhysicalNetworkServiceProviderVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) HashMap(java.util.HashMap) Map(java.util.Map) DB(com.cloud.utils.db.DB)

Example 47 with Host

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

the class DeploymentPlanningManagerImpl method planDeployment.

@Override
public DeployDestination planDeployment(VirtualMachineProfile vmProfile, DeploymentPlan plan, ExcludeList avoids, DeploymentPlanner planner) throws InsufficientServerCapacityException, AffinityConflictException {
    ServiceOffering offering = vmProfile.getServiceOffering();
    int cpu_requested = offering.getCpu() * offering.getSpeed();
    long ram_requested = offering.getRamSize() * 1024L * 1024L;
    VirtualMachine vm = vmProfile.getVirtualMachine();
    DataCenter dc = _dcDao.findById(vm.getDataCenterId());
    if (vm.getType() == VirtualMachine.Type.User || vm.getType() == VirtualMachine.Type.DomainRouter) {
        checkForNonDedicatedResources(vmProfile, dc, avoids);
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("DeploymentPlanner allocation algorithm: " + planner);
        s_logger.debug("Trying to allocate a host and storage pools from dc:" + plan.getDataCenterId() + ", pod:" + plan.getPodId() + ",cluster:" + plan.getClusterId() + ", requested cpu: " + cpu_requested + ", requested ram: " + ram_requested);
        s_logger.debug("Is ROOT volume READY (pool already allocated)?: " + (plan.getPoolId() != null ? "Yes" : "No"));
    }
    String haVmTag = (String) vmProfile.getParameter(VirtualMachineProfile.Param.HaTag);
    if (plan.getHostId() != null && haVmTag == null) {
        Long hostIdSpecified = plan.getHostId();
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("DeploymentPlan has host_id specified, choosing this host and making no checks on this host: " + hostIdSpecified);
        }
        HostVO host = _hostDao.findById(hostIdSpecified);
        if (host == null) {
            s_logger.debug("The specified host cannot be found");
        } else if (avoids.shouldAvoid(host)) {
            s_logger.debug("The specified host is in avoid set");
        } else {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Looking for suitable pools for this host under zone: " + host.getDataCenterId() + ", pod: " + host.getPodId() + ", cluster: " + host.getClusterId());
            }
            Pod pod = _podDao.findById(host.getPodId());
            Cluster cluster = _clusterDao.findById(host.getClusterId());
            if (vm.getHypervisorType() == HypervisorType.BareMetal) {
                DeployDestination dest = new DeployDestination(dc, pod, cluster, host, new HashMap<Volume, StoragePool>());
                s_logger.debug("Returning Deployment Destination: " + dest);
                return dest;
            }
            // search for storage under the zone, pod, cluster of the host.
            DataCenterDeployment lastPlan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), hostIdSpecified, plan.getPoolId(), null, plan.getReservationContext());
            Pair<Map<Volume, List<StoragePool>>, List<Volume>> result = findSuitablePoolsForVolumes(vmProfile, lastPlan, avoids, HostAllocator.RETURN_UPTO_ALL);
            Map<Volume, List<StoragePool>> suitableVolumeStoragePools = result.first();
            List<Volume> readyAndReusedVolumes = result.second();
            // choose the potential pool for this VM for this host
            if (!suitableVolumeStoragePools.isEmpty()) {
                List<Host> suitableHosts = new ArrayList<Host>();
                suitableHosts.add(host);
                Pair<Host, Map<Volume, StoragePool>> potentialResources = findPotentialDeploymentResources(suitableHosts, suitableVolumeStoragePools, avoids, getPlannerUsage(planner, vmProfile, plan, avoids), readyAndReusedVolumes);
                if (potentialResources != null) {
                    pod = _podDao.findById(host.getPodId());
                    cluster = _clusterDao.findById(host.getClusterId());
                    Map<Volume, StoragePool> storageVolMap = potentialResources.second();
                    // we don't have to prepare this volume.
                    for (Volume vol : readyAndReusedVolumes) {
                        storageVolMap.remove(vol);
                    }
                    DeployDestination dest = new DeployDestination(dc, pod, cluster, host, storageVolMap);
                    s_logger.debug("Returning Deployment Destination: " + dest);
                    return dest;
                }
            }
        }
        s_logger.debug("Cannot deploy to specified host, returning.");
        return null;
    }
    // call affinitygroup chain
    long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
    if (vmGroupCount > 0) {
        for (AffinityGroupProcessor processor : _affinityProcessors) {
            processor.process(vmProfile, plan, avoids);
        }
    }
    if (vm.getType() == VirtualMachine.Type.User) {
        checkForNonDedicatedResources(vmProfile, dc, avoids);
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Deploy avoids pods: " + avoids.getPodsToAvoid() + ", clusters: " + avoids.getClustersToAvoid() + ", hosts: " + avoids.getHostsToAvoid());
    }
    // check if datacenter is in avoid set
    if (avoids.shouldAvoid(dc)) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("DataCenter id = '" + dc.getId() + "' provided is in avoid set, DeploymentPlanner cannot allocate the VM, returning.");
        }
        return null;
    }
    if (planner == null) {
        String plannerName = offering.getDeploymentPlanner();
        if (plannerName == null) {
            if (vm.getHypervisorType() == HypervisorType.BareMetal) {
                plannerName = "BareMetalPlanner";
            } else {
                plannerName = _configDao.getValue(Config.VmDeploymentPlanner.key());
            }
        }
        planner = getDeploymentPlannerByName(plannerName);
    }
    if (vm.getLastHostId() != null && haVmTag == null) {
        s_logger.debug("This VM has last host_id specified, trying to choose the same host: " + vm.getLastHostId());
        HostVO host = _hostDao.findById(vm.getLastHostId());
        ServiceOfferingDetailsVO offeringDetails = null;
        if (host == null) {
            s_logger.debug("The last host of this VM cannot be found");
        } else if (avoids.shouldAvoid(host)) {
            s_logger.debug("The last host of this VM is in avoid set");
        } else if (plan.getClusterId() != null && host.getClusterId() != null && !plan.getClusterId().equals(host.getClusterId())) {
            s_logger.debug("The last host of this VM cannot be picked as the plan specifies different clusterId: " + plan.getClusterId());
        } else if (_capacityMgr.checkIfHostReachMaxGuestLimit(host)) {
            s_logger.debug("The last Host, hostId: " + host.getId() + " already has max Running VMs(count includes system VMs), skipping this and trying other available hosts");
        } else if ((offeringDetails = _serviceOfferingDetailsDao.findDetail(offering.getId(), GPU.Keys.vgpuType.toString())) != null) {
            ServiceOfferingDetailsVO groupName = _serviceOfferingDetailsDao.findDetail(offering.getId(), GPU.Keys.pciDevice.toString());
            if (!_resourceMgr.isGPUDeviceAvailable(host.getId(), groupName.getValue(), offeringDetails.getValue())) {
                s_logger.debug("The last host of this VM does not have required GPU devices available");
            }
        } else {
            if (host.getStatus() == Status.Up && host.getResourceState() == ResourceState.Enabled) {
                boolean hostTagsMatch = true;
                if (offering.getHostTag() != null) {
                    _hostDao.loadHostTags(host);
                    if (!(host.getHostTags() != null && host.getHostTags().contains(offering.getHostTag()))) {
                        hostTagsMatch = false;
                    }
                }
                if (hostTagsMatch) {
                    long cluster_id = host.getClusterId();
                    ClusterDetailsVO cluster_detail_cpu = _clusterDetailsDao.findDetail(cluster_id, "cpuOvercommitRatio");
                    ClusterDetailsVO cluster_detail_ram = _clusterDetailsDao.findDetail(cluster_id, "memoryOvercommitRatio");
                    Float cpuOvercommitRatio = Float.parseFloat(cluster_detail_cpu.getValue());
                    Float memoryOvercommitRatio = Float.parseFloat(cluster_detail_ram.getValue());
                    boolean hostHasCpuCapability, hostHasCapacity = false;
                    hostHasCpuCapability = _capacityMgr.checkIfHostHasCpuCapability(host.getId(), offering.getCpu(), offering.getSpeed());
                    if (hostHasCpuCapability) {
                        // first check from reserved capacity
                        hostHasCapacity = _capacityMgr.checkIfHostHasCapacity(host.getId(), cpu_requested, ram_requested, true, cpuOvercommitRatio, memoryOvercommitRatio, true);
                        // if not reserved, check the free capacity
                        if (!hostHasCapacity)
                            hostHasCapacity = _capacityMgr.checkIfHostHasCapacity(host.getId(), cpu_requested, ram_requested, false, cpuOvercommitRatio, memoryOvercommitRatio, true);
                    }
                    if (hostHasCapacity && hostHasCpuCapability) {
                        s_logger.debug("The last host of this VM is UP and has enough capacity");
                        s_logger.debug("Now checking for suitable pools under zone: " + host.getDataCenterId() + ", pod: " + host.getPodId() + ", cluster: " + host.getClusterId());
                        Pod pod = _podDao.findById(host.getPodId());
                        Cluster cluster = _clusterDao.findById(host.getClusterId());
                        if (vm.getHypervisorType() == HypervisorType.BareMetal) {
                            DeployDestination dest = new DeployDestination(dc, pod, cluster, host, new HashMap<Volume, StoragePool>());
                            s_logger.debug("Returning Deployment Destination: " + dest);
                            return dest;
                        }
                        // search for storage under the zone, pod, cluster
                        // of
                        // the last host.
                        DataCenterDeployment lastPlan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), host.getId(), plan.getPoolId(), null);
                        Pair<Map<Volume, List<StoragePool>>, List<Volume>> result = findSuitablePoolsForVolumes(vmProfile, lastPlan, avoids, HostAllocator.RETURN_UPTO_ALL);
                        Map<Volume, List<StoragePool>> suitableVolumeStoragePools = result.first();
                        List<Volume> readyAndReusedVolumes = result.second();
                        // host
                        if (!suitableVolumeStoragePools.isEmpty()) {
                            List<Host> suitableHosts = new ArrayList<Host>();
                            suitableHosts.add(host);
                            Pair<Host, Map<Volume, StoragePool>> potentialResources = findPotentialDeploymentResources(suitableHosts, suitableVolumeStoragePools, avoids, getPlannerUsage(planner, vmProfile, plan, avoids), readyAndReusedVolumes);
                            if (potentialResources != null) {
                                Map<Volume, StoragePool> storageVolMap = potentialResources.second();
                                // this volume.
                                for (Volume vol : readyAndReusedVolumes) {
                                    storageVolMap.remove(vol);
                                }
                                DeployDestination dest = new DeployDestination(dc, pod, cluster, host, storageVolMap);
                                s_logger.debug("Returning Deployment Destination: " + dest);
                                return dest;
                            }
                        }
                    } else {
                        s_logger.debug("The last host of this VM does not have enough capacity");
                    }
                } else {
                    s_logger.debug("Service Offering host tag does not match the last host of this VM");
                }
            } else {
                s_logger.debug("The last host of this VM is not UP or is not enabled, host status is: " + host.getStatus().name() + ", host resource state is: " + host.getResourceState());
            }
        }
        s_logger.debug("Cannot choose the last host to deploy this VM ");
    }
    DeployDestination dest = null;
    List<Long> clusterList = null;
    if (planner != null && planner.canHandle(vmProfile, plan, avoids)) {
        while (true) {
            if (planner instanceof DeploymentClusterPlanner) {
                ExcludeList plannerAvoidInput = new ExcludeList(avoids.getDataCentersToAvoid(), avoids.getPodsToAvoid(), avoids.getClustersToAvoid(), avoids.getHostsToAvoid(), avoids.getPoolsToAvoid());
                clusterList = ((DeploymentClusterPlanner) planner).orderClusters(vmProfile, plan, avoids);
                if (clusterList != null && !clusterList.isEmpty()) {
                    // planner refactoring. call allocators to list hosts
                    ExcludeList plannerAvoidOutput = new ExcludeList(avoids.getDataCentersToAvoid(), avoids.getPodsToAvoid(), avoids.getClustersToAvoid(), avoids.getHostsToAvoid(), avoids.getPoolsToAvoid());
                    resetAvoidSet(plannerAvoidOutput, plannerAvoidInput);
                    dest = checkClustersforDestination(clusterList, vmProfile, plan, avoids, dc, getPlannerUsage(planner, vmProfile, plan, avoids), plannerAvoidOutput);
                    if (dest != null) {
                        return dest;
                    }
                    // reset the avoid input to the planners
                    resetAvoidSet(avoids, plannerAvoidOutput);
                } else {
                    return null;
                }
            } else {
                dest = planner.plan(vmProfile, plan, avoids);
                if (dest != null) {
                    long hostId = dest.getHost().getId();
                    avoids.addHost(dest.getHost().getId());
                    if (checkIfHostFitsPlannerUsage(hostId, DeploymentPlanner.PlannerResourceUsage.Shared)) {
                        // found destination
                        return dest;
                    } else {
                        // deployment picked it up for dedicated access
                        continue;
                    }
                } else {
                    return null;
                }
            }
        }
    }
    return dest;
}
Also used : StoragePool(com.cloud.storage.StoragePool) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ServiceOfferingDetailsVO(com.cloud.service.ServiceOfferingDetailsVO) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) AffinityGroupProcessor(org.apache.cloudstack.affinity.AffinityGroupProcessor) Pair(com.cloud.utils.Pair) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) Pod(com.cloud.dc.Pod) ServiceOffering(com.cloud.offering.ServiceOffering) Cluster(com.cloud.org.Cluster) Host(com.cloud.host.Host) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) HostVO(com.cloud.host.HostVO) DataCenter(com.cloud.dc.DataCenter) Volume(com.cloud.storage.Volume) Map(java.util.Map) HashMap(java.util.HashMap) ClusterDetailsVO(com.cloud.dc.ClusterDetailsVO) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 48 with Host

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

the class DeploymentPlanningManagerImpl method findPotentialDeploymentResources.

protected Pair<Host, Map<Volume, StoragePool>> findPotentialDeploymentResources(List<Host> suitableHosts, Map<Volume, List<StoragePool>> suitableVolumeStoragePools, ExcludeList avoid, DeploymentPlanner.PlannerResourceUsage resourceUsageRequired, List<Volume> readyAndReusedVolumes) {
    s_logger.debug("Trying to find a potenial host and associated storage pools from the suitable host/pool lists for this VM");
    boolean hostCanAccessPool = false;
    boolean haveEnoughSpace = false;
    if (readyAndReusedVolumes == null) {
        readyAndReusedVolumes = new ArrayList<Volume>();
    }
    Map<Volume, StoragePool> storage = new HashMap<Volume, StoragePool>();
    TreeSet<Volume> volumesOrderBySizeDesc = new TreeSet<Volume>(new Comparator<Volume>() {

        @Override
        public int compare(Volume v1, Volume v2) {
            if (v1.getSize() < v2.getSize())
                return 1;
            else
                return -1;
        }
    });
    volumesOrderBySizeDesc.addAll(suitableVolumeStoragePools.keySet());
    boolean multipleVolume = volumesOrderBySizeDesc.size() > 1;
    for (Host potentialHost : suitableHosts) {
        Map<StoragePool, List<Volume>> volumeAllocationMap = new HashMap<StoragePool, List<Volume>>();
        for (Volume vol : volumesOrderBySizeDesc) {
            haveEnoughSpace = false;
            s_logger.debug("Checking if host: " + potentialHost.getId() + " can access any suitable storage pool for volume: " + vol.getVolumeType());
            List<StoragePool> volumePoolList = suitableVolumeStoragePools.get(vol);
            hostCanAccessPool = false;
            for (StoragePool potentialSPool : volumePoolList) {
                if (hostCanAccessSPool(potentialHost, potentialSPool)) {
                    hostCanAccessPool = true;
                    if (multipleVolume && !readyAndReusedVolumes.contains(vol)) {
                        List<Volume> requestVolumes = null;
                        if (volumeAllocationMap.containsKey(potentialSPool))
                            requestVolumes = volumeAllocationMap.get(potentialSPool);
                        else
                            requestVolumes = new ArrayList<Volume>();
                        requestVolumes.add(vol);
                        if (!_storageMgr.storagePoolHasEnoughIops(requestVolumes, potentialSPool) || !_storageMgr.storagePoolHasEnoughSpace(requestVolumes, potentialSPool, potentialHost.getClusterId()))
                            continue;
                        volumeAllocationMap.put(potentialSPool, requestVolumes);
                    }
                    storage.put(vol, potentialSPool);
                    haveEnoughSpace = true;
                    break;
                }
            }
            if (!hostCanAccessPool) {
                break;
            }
            if (!haveEnoughSpace) {
                s_logger.warn("insufficient capacity to allocate all volumes");
                break;
            }
        }
        if (hostCanAccessPool && haveEnoughSpace && checkIfHostFitsPlannerUsage(potentialHost.getId(), resourceUsageRequired)) {
            s_logger.debug("Found a potential host " + "id: " + potentialHost.getId() + " name: " + potentialHost.getName() + " and associated storage pools for this VM");
            return new Pair<Host, Map<Volume, StoragePool>>(potentialHost, storage);
        } else {
            avoid.addHost(potentialHost.getId());
        }
    }
    s_logger.debug("Could not find a potential host that has associated storage pools from the suitable host/pool lists for this VM");
    return null;
}
Also used : StoragePool(com.cloud.storage.StoragePool) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Host(com.cloud.host.Host) Volume(com.cloud.storage.Volume) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) Pair(com.cloud.utils.Pair)

Example 49 with Host

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

the class CiscoNexusVSMDeviceManagerImpl method deleteCiscoNexusVSM.

@DB
public boolean deleteCiscoNexusVSM(final long vsmId) throws ResourceInUseException {
    CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId);
    if (cisconexusvsm == null) {
        // This entry is already not present. Return success.
        return true;
    }
    // First, check whether this VSM is part of any non-empty cluster.
    // Search ClusterVSMMap's table for a list of clusters using this vsmId.
    List<ClusterVSMMapVO> clusterList = _clusterVSMDao.listByVSMId(vsmId);
    if (clusterList != null) {
        for (ClusterVSMMapVO record : clusterList) {
            // If this cluster id has any hosts in it, fail this operation.
            Long clusterId = record.getClusterId();
            List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
            if (hosts != null && hosts.size() > 0) {
                for (Host host : hosts) {
                    if (host.getType() == Host.Type.Routing) {
                        s_logger.info("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first");
                        throw new ResourceInUseException("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first");
                    }
                }
            }
        }
    }
    // Iterate through the cluster list again, this time, delete the VSM.
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            // Remove the VSM entry in CiscoNexusVSMDeviceVO's table.
            _ciscoNexusVSMDeviceDao.remove(vsmId);
            // Remove the current record as well from ClusterVSMMapVO's table.
            _clusterVSMDao.removeByVsmId(vsmId);
        }
    });
    return true;
}
Also used : ClusterVSMMapVO(com.cloud.dc.ClusterVSMMapVO) ResourceInUseException(com.cloud.exception.ResourceInUseException) TransactionStatus(com.cloud.utils.db.TransactionStatus) Host(com.cloud.host.Host) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) HostVO(com.cloud.host.HostVO) DB(com.cloud.utils.db.DB)

Example 50 with Host

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

the class CiscoVnmcElement method addCiscoVnmcResource.

@Override
public CiscoVnmcController addCiscoVnmcResource(AddCiscoVnmcResourceCmd cmd) {
    final String deviceName = Provider.CiscoVnmc.getName();
    NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName);
    final Long physicalNetworkId = cmd.getPhysicalNetworkId();
    CiscoVnmcController ciscoVnmcResource = null;
    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 (_ciscoVnmcDao.listByPhysicalNetwork(physicalNetworkId).size() != 0) {
        throw new CloudRuntimeException("A Cisco Vnmc device is already configured on this physical network");
    }
    Map<String, String> params = new HashMap<String, String>();
    params.put("guid", UUID.randomUUID().toString());
    params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId()));
    params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId()));
    params.put("name", "Cisco VNMC Controller - " + cmd.getHost());
    params.put("ip", cmd.getHost());
    params.put("username", cmd.getUsername());
    params.put("password", cmd.getPassword());
    Map<String, Object> hostdetails = new HashMap<String, Object>();
    hostdetails.putAll(params);
    ServerResource resource = new CiscoVnmcResource();
    try {
        resource.configure(cmd.getHost(), hostdetails);
        final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalFirewall, params);
        if (host != null) {
            return Transaction.execute(new TransactionCallback<CiscoVnmcController>() {

                @Override
                public CiscoVnmcController doInTransaction(TransactionStatus status) {
                    CiscoVnmcController ciscoVnmcResource = new CiscoVnmcControllerVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName);
                    _ciscoVnmcDao.persist((CiscoVnmcControllerVO) ciscoVnmcResource);
                    DetailVO detail = new DetailVO(host.getId(), "deviceid", String.valueOf(ciscoVnmcResource.getId()));
                    _hostDetailsDao.persist(detail);
                    return ciscoVnmcResource;
                }
            });
        } else {
            throw new CloudRuntimeException("Failed to add Cisco Vnmc device due to internal error.");
        }
    } catch (ConfigurationException e) {
        throw new CloudRuntimeException(e.getMessage());
    }
}
Also used : HashMap(java.util.HashMap) NetworkDevice(org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice) ServerResource(com.cloud.resource.ServerResource) TransactionStatus(com.cloud.utils.db.TransactionStatus) Host(com.cloud.host.Host) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) DetailVO(com.cloud.host.DetailVO) ConfigurationException(javax.naming.ConfigurationException) PhysicalNetworkServiceProviderVO(com.cloud.network.dao.PhysicalNetworkServiceProviderVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CiscoVnmcResource(com.cloud.network.resource.CiscoVnmcResource) CiscoVnmcController(com.cloud.network.cisco.CiscoVnmcController) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) CiscoVnmcControllerVO(com.cloud.network.cisco.CiscoVnmcControllerVO)

Aggregations

Host (com.cloud.host.Host)112 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)37 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)31 ArrayList (java.util.ArrayList)31 HashMap (java.util.HashMap)29 ServerApiException (org.apache.cloudstack.api.ServerApiException)20 ConfigurationException (javax.naming.ConfigurationException)17 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)16 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)16 DB (com.cloud.utils.db.DB)14 Map (java.util.Map)14 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)13 PhysicalNetworkServiceProviderVO (com.cloud.network.dao.PhysicalNetworkServiceProviderVO)13 Answer (com.cloud.agent.api.Answer)11 TransactionStatus (com.cloud.utils.db.TransactionStatus)11 DataCenter (com.cloud.dc.DataCenter)10 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)10 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)10 HostVO (com.cloud.host.HostVO)9 StoragePool (com.cloud.storage.StoragePool)9