Search in sources :

Example 81 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cosmic by MissionCriticalCloud.

the class AddIpToVmNicCmd method getEntityOwnerId.

@Override
public long getEntityOwnerId() {
    final Nic nic = _entityMgr.findById(Nic.class, nicId);
    if (nic == null) {
        throw new InvalidParameterValueException("Can't find nic for id specified");
    }
    final long vmId = nic.getInstanceId();
    final VirtualMachine vm = _entityMgr.findById(VirtualMachine.class, vmId);
    return vm.getAccountId();
}
Also used : InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) Nic(com.cloud.vm.Nic) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 82 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method releaseSecondaryIpFromNic.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_UNASSIGN, eventDescription = "Removing secondary ip " + "from nic", async = true)
public boolean releaseSecondaryIpFromNic(final long ipAddressId) {
    final Account caller = CallContext.current().getCallingAccount();
    boolean success = false;
    // Verify input parameters
    final NicSecondaryIpVO secIpVO = _nicSecondaryIpDao.findById(ipAddressId);
    if (secIpVO == null) {
        throw new InvalidParameterValueException("Unable to find secondary ip address by id");
    }
    final VirtualMachine vm = _userVmDao.findById(secIpVO.getVmId());
    if (vm == null) {
        throw new InvalidParameterValueException("There is no vm with the given secondary ip");
    }
    // verify permissions
    _accountMgr.checkAccess(caller, null, true, vm);
    final Network network = _networksDao.findById(secIpVO.getNetworkId());
    if (network == null) {
        throw new InvalidParameterValueException("Invalid network id is given");
    }
    // Validate network offering
    final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(network.getNetworkOfferingId());
    final Long nicId = secIpVO.getNicId();
    s_logger.debug("ip id = " + ipAddressId + " nic id = " + nicId);
    // check is this the last secondary ip for NIC
    final List<NicSecondaryIpVO> ipList = _nicSecondaryIpDao.listByNicId(nicId);
    boolean lastIp = false;
    if (ipList.size() == 1) {
        // this is the last secondary ip to nic
        lastIp = true;
    }
    final DataCenter dc = _dcDao.findById(network.getDataCenterId());
    if (dc == null) {
        throw new InvalidParameterValueException("Invalid zone Id is given");
    }
    s_logger.debug("Calling secondary ip " + secIpVO.getIp4Address() + " release ");
    if (dc.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) {
        // check PF or static NAT is configured on this ip address
        final String secondaryIp = secIpVO.getIp4Address();
        final List<FirewallRuleVO> fwRulesList = _firewallDao.listByNetworkAndPurpose(network.getId(), Purpose.PortForwarding);
        if (fwRulesList.size() != 0) {
            for (final FirewallRuleVO rule : fwRulesList) {
                if (_portForwardingDao.findByIdAndIp(rule.getId(), secondaryIp) != null) {
                    s_logger.debug("VM nic IP " + secondaryIp + " is associated with the port forwarding rule");
                    throw new InvalidParameterValueException("Can't remove the secondary ip " + secondaryIp + " is associate with the port forwarding rule");
                }
            }
        }
        // check if the secondary ip associated with any static nat rule
        final IPAddressVO publicIpVO = _ipAddressDao.findByIpAndNetworkId(secIpVO.getNetworkId(), secondaryIp);
        if (publicIpVO != null) {
            s_logger.debug("VM nic IP " + secondaryIp + " is associated with the static NAT rule public IP address id " + publicIpVO.getId());
            throw new InvalidParameterValueException("Can' remove the ip " + secondaryIp + "is associate with static NAT rule public IP address id " + publicIpVO.getId());
        }
        if (_lbService.isLbRuleMappedToVmGuestIp(secondaryIp)) {
            s_logger.debug("VM nic IP " + secondaryIp + " is mapped to load balancing rule");
            throw new InvalidParameterValueException("Can't remove the secondary ip " + secondaryIp + " is mapped to load balancing rule");
        }
    } else if (dc.getNetworkType() == NetworkType.Basic || ntwkOff.getGuestType() == Network.GuestType.Shared) {
        final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address());
        if (ip != null) {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    _ipAddrMgr.markIpAsUnavailable(ip.getId());
                    _ipAddressDao.unassignIpAddress(ip.getId());
                }
            });
        }
    } else if (network.getTrafficType() == TrafficType.Public) {
        final IPAddressVO publicIpVO = _ipAddressDao.findByIpAndSourceNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address());
        final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
        final Account callerAccount = _accountMgr.getActiveAccountById(callerUser.getAccountId());
        _ipAddrMgr.disassociatePublicIpAddress(publicIpVO.getId(), callerUser.getId(), callerAccount);
    } else {
        throw new InvalidParameterValueException("Not supported for this network now");
    }
    success = removeNicSecondaryIP(secIpVO, lastIp);
    return success;
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) NicSecondaryIpVO(com.cloud.vm.dao.NicSecondaryIpVO) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) VirtualMachine(com.cloud.vm.VirtualMachine) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 83 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method allocateSecondaryGuestIP.

@Override
@ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_ASSIGN, eventDescription = "assigning secondary ip to nic", create = true)
public NicSecondaryIp allocateSecondaryGuestIP(final long nicId, final String requestedIp) throws InsufficientAddressCapacityException {
    final Account caller = CallContext.current().getCallingAccount();
    // check whether the nic belongs to user vm.
    final NicVO nicVO = _nicDao.findById(nicId);
    if (nicVO == null) {
        throw new InvalidParameterValueException("There is no nic for the " + nicId);
    }
    if (nicVO.getVmType() != VirtualMachine.Type.User) {
        throw new InvalidParameterValueException("The nic is not belongs to user vm");
    }
    final VirtualMachine vm = _userVmDao.findById(nicVO.getInstanceId());
    if (vm == null) {
        throw new InvalidParameterValueException("There is no vm with the nic");
    }
    final long networkId = nicVO.getNetworkId();
    final Account ipOwner = _accountMgr.getAccount(vm.getAccountId());
    // verify permissions
    _accountMgr.checkAccess(caller, null, true, vm);
    final Network network = _networksDao.findById(networkId);
    if (network == null) {
        throw new InvalidParameterValueException("Invalid network id is given");
    }
    final int maxAllowedIpsPerNic = NumbersUtil.parseInt(_configDao.getValue(Config.MaxNumberOfSecondaryIPsPerNIC.key()), 10);
    final Long nicWiseIpCount = _nicSecondaryIpDao.countByNicId(nicId);
    if (nicWiseIpCount.intValue() >= maxAllowedIpsPerNic) {
        s_logger.error("Maximum Number of Ips \"vm.network.nic.max.secondary.ipaddresses = \"" + maxAllowedIpsPerNic + " per Nic has been crossed for the nic " + nicId + ".");
        throw new InsufficientAddressCapacityException("Maximum Number of Ips per Nic has been crossed.", Nic.class, nicId);
    }
    s_logger.debug("Calling the ip allocation ...");
    String ipaddr = null;
    // Isolated network can exist in Basic zone only, so no need to verify the zone type
    if (network.getGuestType() == Network.GuestType.Isolated) {
        try {
            ipaddr = _ipAddrMgr.allocateGuestIP(network, requestedIp);
        } catch (final InsufficientAddressCapacityException e) {
            throw new InvalidParameterValueException("Allocating guest ip for nic failed");
        }
    } else if (network.getGuestType() == Network.GuestType.Shared) {
        // for basic zone, need to provide the podId to ensure proper ip alloation
        Long podId = null;
        final DataCenter dc = _dcDao.findById(network.getDataCenterId());
        if (dc.getNetworkType() == NetworkType.Basic) {
            final VMInstanceVO vmi = (VMInstanceVO) vm;
            podId = vmi.getPodIdToDeployIn();
            if (podId == null) {
                throw new InvalidParameterValueException("vm pod id is null in Basic zone; can't decide the range for ip allocation");
            }
        }
        try {
            ipaddr = _ipAddrMgr.allocatePublicIpForGuestNic(network, podId, ipOwner, requestedIp);
            if (ipaddr == null) {
                throw new InvalidParameterValueException("Allocating ip to guest nic " + nicId + " failed");
            }
        } catch (final InsufficientAddressCapacityException e) {
            s_logger.error("Allocating ip to guest nic " + nicId + " failed");
            return null;
        }
    } else if (network.getTrafficType() == TrafficType.Public) {
        try {
            final PublicIp ip = _ipAddrMgr.assignPublicIpAddress(vm.getDataCenterId(), null, ipOwner, VlanType.VirtualNetwork, null, requestedIp, false);
            ipaddr = ip.getAddress().toString();
        } catch (final InsufficientAddressCapacityException e) {
            throw new InvalidParameterValueException("Allocating public ip for nic failed");
        }
    } else {
        s_logger.error("AddIpToVMNic is not supported in this network...");
        return null;
    }
    if (ipaddr != null) {
        // we got the ip addr so up the nics table and secondary ip
        final String addrFinal = ipaddr;
        final long id = Transaction.execute(new TransactionCallback<Long>() {

            @Override
            public Long doInTransaction(final TransactionStatus status) {
                final boolean nicSecondaryIpSet = nicVO.getSecondaryIp();
                if (!nicSecondaryIpSet) {
                    nicVO.setSecondaryIp(true);
                    // commit when previously set ??
                    s_logger.debug("Setting nics table ...");
                    _nicDao.update(nicId, nicVO);
                }
                s_logger.debug("Setting nic_secondary_ip table ...");
                final Long vmId = nicVO.getInstanceId();
                final NicSecondaryIpVO secondaryIpVO = new NicSecondaryIpVO(nicId, addrFinal, vmId, ipOwner.getId(), ipOwner.getDomainId(), networkId);
                _nicSecondaryIpDao.persist(secondaryIpVO);
                return secondaryIpVO.getId();
            }
        });
        return getNicSecondaryIp(id);
    } else {
        return null;
    }
}
Also used : Account(com.cloud.user.Account) PublicIp(com.cloud.network.addr.PublicIp) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) VMInstanceVO(com.cloud.vm.VMInstanceVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) NicSecondaryIpVO(com.cloud.vm.dao.NicSecondaryIpVO) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) NicVO(com.cloud.vm.NicVO) VirtualMachine(com.cloud.vm.VirtualMachine) ActionEvent(com.cloud.event.ActionEvent)

Example 84 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cosmic by MissionCriticalCloud.

the class HighAvailabilityManagerImpl method destroyVM.

protected Long destroyVM(final HaWorkVO work) {
    final VirtualMachine vm = _itMgr.findById(work.getInstanceId());
    s_logger.info("Destroying " + vm.toString());
    try {
        if (vm.getState() != State.Destroyed) {
            s_logger.info("VM is no longer in Destroyed state " + vm.toString());
            return null;
        }
        if (vm.getHostId() != null) {
            _itMgr.destroy(vm.getUuid());
            s_logger.info("Successfully destroy " + vm);
            return null;
        } else {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug(vm + " has already been stopped");
            }
            return null;
        }
    } catch (final AgentUnavailableException e) {
        s_logger.debug("Agnet is not available" + e.getMessage());
    } catch (final OperationTimedoutException e) {
        s_logger.debug("operation timed out: " + e.getMessage());
    } catch (final ConcurrentOperationException e) {
        s_logger.debug("concurrent operation: " + e.getMessage());
    }
    return (System.currentTimeMillis() >> 10) + _stopRetryInterval;
}
Also used : OperationTimedoutException(com.cloud.exception.OperationTimedoutException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 85 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cosmic by MissionCriticalCloud.

the class DeploymentPlanningManagerImpl method planDeployment.

@Override
public DeployDestination planDeployment(final VirtualMachineProfile vmProfile, final DeploymentPlan plan, final ExcludeList avoids, DeploymentPlanner planner) throws InsufficientServerCapacityException, AffinityConflictException {
    // call affinitygroup chain
    final VirtualMachine vm = vmProfile.getVirtualMachine();
    final long vmGroupCount = _affinityGroupVMMapDao.countAffinityGroupsForVm(vm.getId());
    final Zone zone = zoneRepository.findOne(vm.getDataCenterId());
    if (vmGroupCount > 0) {
        for (final AffinityGroupProcessor processor : _affinityProcessors) {
            processor.process(vmProfile, plan, avoids);
        }
    }
    if (vm.getType() == VirtualMachine.Type.User || vm.getType() == VirtualMachine.Type.DomainRouter) {
        checkForNonDedicatedResources(vmProfile, zone, avoids);
    }
    s_logger.debug("Deployment will {}", avoids.toString());
    // check if datacenter is in avoid set
    if (avoids.shouldAvoid(zone)) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("DataCenter id = '" + zone.getId() + "' provided is in avoid set, DeploymentPlanner cannot allocate the VM, returning.");
        }
        return null;
    }
    final ServiceOffering offering = vmProfile.getServiceOffering();
    if (planner == null) {
        String plannerName = offering.getDeploymentPlanner();
        if (plannerName == null) {
            plannerName = _configDao.getValue(Config.VmDeploymentPlanner.key());
        }
        planner = getDeploymentPlannerByName(plannerName);
    }
    final int cpu_requested = offering.getCpu();
    final long ram_requested = offering.getRamSize() * 1024L * 1024L;
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("DeploymentPlanner allocation algorithm: " + planner);
        s_logger.debug("Trying to allocate a host and storage pools from zone:" + 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"));
    }
    final String haVmTag = (String) vmProfile.getParameter(VirtualMachineProfile.Param.HaTag);
    if (plan.getHostId() != null && haVmTag == null) {
        final 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);
        }
        final 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());
            // search for storage under the zone, pod, cluster of the host.
            final DataCenterDeployment lastPlan = new DataCenterDeployment(host.getDataCenterId(), host.getPodId(), host.getClusterId(), hostIdSpecified, plan.getPoolId(), null, plan.getReservationContext());
            final Pair<Map<Volume, List<StoragePool>>, List<Volume>> result = findSuitablePoolsForVolumes(vmProfile, lastPlan, avoids, HostAllocator.RETURN_UPTO_ALL);
            final Map<Volume, List<StoragePool>> suitableVolumeStoragePools = result.first();
            final List<Volume> readyAndReusedVolumes = result.second();
            // choose the potential pool for this VM for this host
            if (!suitableVolumeStoragePools.isEmpty()) {
                final List<Host> suitableHosts = new ArrayList<>();
                suitableHosts.add(host);
                final 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());
                    final Map<Volume, StoragePool> storageVolMap = potentialResources.second();
                    // we don't have to prepare this volume.
                    for (final Volume vol : readyAndReusedVolumes) {
                        storageVolMap.remove(vol);
                    }
                    final DeployDestination dest = new DeployDestination(zone, pod, cluster, host, storageVolMap);
                    s_logger.debug("Returning Deployment Destination: " + dest);
                    return dest;
                }
            }
        }
        s_logger.debug("Cannot deploy to specified host, returning.");
        return null;
    }
    DeployDestination dest = null;
    List<Long> clusterList = null;
    if (planner != null && planner.canHandle(vmProfile, plan, avoids)) {
        while (true) {
            if (planner instanceof DeploymentClusterPlanner) {
                final ExcludeList plannerAvoidInput = new ExcludeList(avoids.getZonesToAvoid(), 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
                    final ExcludeList plannerAvoidOutput = new ExcludeList(avoids.getZonesToAvoid(), avoids.getPodsToAvoid(), avoids.getClustersToAvoid(), avoids.getHostsToAvoid(), avoids.getPoolsToAvoid());
                    resetAvoidSet(plannerAvoidOutput, plannerAvoidInput);
                    dest = checkClustersforDestination(clusterList, vmProfile, plan, avoids, zone, 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) {
                    final 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 : ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) StoragePool(com.cloud.storage.StoragePool) Pod(com.cloud.dc.Pod) ServiceOffering(com.cloud.offering.ServiceOffering) Zone(com.cloud.db.model.Zone) Cluster(com.cloud.org.Cluster) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) HostVO(com.cloud.host.HostVO) Volume(com.cloud.storage.Volume) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) AffinityGroupProcessor(com.cloud.affinity.AffinityGroupProcessor) Map(java.util.Map) HashMap(java.util.HashMap) VirtualMachine(com.cloud.vm.VirtualMachine) Pair(com.cloud.utils.Pair)

Aggregations

VirtualMachine (com.cloud.vm.VirtualMachine)141 HostVO (com.cloud.host.HostVO)38 ArrayList (java.util.ArrayList)35 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)26 HashMap (java.util.HashMap)25 List (java.util.List)23 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)21 VMInstanceVO (com.cloud.vm.VMInstanceVO)20 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)19 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)19 DataCenter (com.cloud.dc.DataCenter)17 Host (com.cloud.host.Host)17 ServiceOffering (com.cloud.offering.ServiceOffering)17 Test (org.junit.Test)17 ServerApiException (com.cloud.api.ServerApiException)16 SystemVmResponse (com.cloud.api.response.SystemVmResponse)14 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)14 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)13 Account (com.cloud.user.Account)13 UserVm (com.cloud.uservm.UserVm)13