Search in sources :

Example 16 with UserVmVO

use of com.cloud.vm.UserVmVO in project cloudstack by apache.

the class RulesManagerImpl method enableStaticNat.

private boolean enableStaticNat(long ipId, long vmId, long networkId, boolean isSystemVm, String vmGuestIp) throws NetworkRuleConflictException, ResourceUnavailableException {
    CallContext ctx = CallContext.current();
    Account caller = ctx.getCallingAccount();
    CallContext.current().setEventDetails("Ip Id: " + ipId);
    // Verify input parameters
    IPAddressVO ipAddress = _ipAddressDao.findById(ipId);
    if (ipAddress == null) {
        throw new InvalidParameterValueException("Unable to find ip address by id " + ipId);
    }
    // Verify input parameters
    boolean performedIpAssoc = false;
    boolean isOneToOneNat = ipAddress.isOneToOneNat();
    Long associatedWithVmId = ipAddress.getAssociatedWithVmId();
    Nic guestNic;
    NicSecondaryIpVO nicSecIp = null;
    String dstIp = null;
    try {
        Network network = _networkModel.getNetwork(networkId);
        if (network == null) {
            throw new InvalidParameterValueException("Unable to find network by id");
        }
        // Check that vm has a nic in the network
        guestNic = _networkModel.getNicInNetwork(vmId, networkId);
        if (guestNic == null) {
            throw new InvalidParameterValueException("Vm doesn't belong to the network with specified id");
        }
        dstIp = guestNic.getIPv4Address();
        if (!_networkModel.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
            throw new InvalidParameterValueException("Unable to create static nat rule; StaticNat service is not " + "supported in network with specified id");
        }
        if (!isSystemVm) {
            UserVmVO vm = _vmDao.findById(vmId);
            if (vm == null) {
                throw new InvalidParameterValueException("Can't enable static nat for the address id=" + ipId + ", invalid virtual machine id specified (" + vmId + ").");
            }
            //associate ip address to network (if needed)
            if (ipAddress.getAssociatedWithNetworkId() == null) {
                boolean assignToVpcNtwk = network.getVpcId() != null && ipAddress.getVpcId() != null && ipAddress.getVpcId().longValue() == network.getVpcId();
                if (assignToVpcNtwk) {
                    _networkModel.checkIpForService(ipAddress, Service.StaticNat, networkId);
                    s_logger.debug("The ip is not associated with the VPC network id=" + networkId + ", so assigning");
                    try {
                        ipAddress = _ipAddrMgr.associateIPToGuestNetwork(ipId, networkId, false);
                    } catch (Exception ex) {
                        s_logger.warn("Failed to associate ip id=" + ipId + " to VPC network id=" + networkId + " as " + "a part of enable static nat");
                        return false;
                    }
                } else if (ipAddress.isPortable()) {
                    s_logger.info("Portable IP " + ipAddress.getUuid() + " is not associated with the network yet " + " so associate IP with the network " + networkId);
                    try {
                        // check if StaticNat service is enabled in the network
                        _networkModel.checkIpForService(ipAddress, Service.StaticNat, networkId);
                        // associate portable IP to vpc, if network is part of VPC
                        if (network.getVpcId() != null) {
                            _vpcSvc.associateIPToVpc(ipId, network.getVpcId());
                        }
                        // associate portable IP with guest network
                        ipAddress = _ipAddrMgr.associatePortableIPToGuestNetwork(ipId, networkId, false);
                    } catch (Exception e) {
                        s_logger.warn("Failed to associate portable id=" + ipId + " to network id=" + networkId + " as " + "a part of enable static nat");
                        return false;
                    }
                }
            } else if (ipAddress.getAssociatedWithNetworkId() != networkId) {
                if (ipAddress.isPortable()) {
                    // check if destination network has StaticNat service enabled
                    _networkModel.checkIpForService(ipAddress, Service.StaticNat, networkId);
                    // check if portable IP can be transferred across the networks
                    if (_ipAddrMgr.isPortableIpTransferableFromNetwork(ipId, ipAddress.getAssociatedWithNetworkId())) {
                        try {
                            // transfer the portable IP and refresh IP details
                            _ipAddrMgr.transferPortableIP(ipId, ipAddress.getAssociatedWithNetworkId(), networkId);
                            ipAddress = _ipAddressDao.findById(ipId);
                        } catch (Exception e) {
                            s_logger.warn("Failed to associate portable id=" + ipId + " to network id=" + networkId + " as " + "a part of enable static nat");
                            return false;
                        }
                    } else {
                        throw new InvalidParameterValueException("Portable IP: " + ipId + " has associated services " + "in network " + ipAddress.getAssociatedWithNetworkId() + " so can not be transferred to " + " network " + networkId);
                    }
                } else {
                    throw new InvalidParameterValueException("Invalid network Id=" + networkId + ". IP is associated with" + " a different network than passed network id");
                }
            } else {
                _networkModel.checkIpForService(ipAddress, Service.StaticNat, null);
            }
            if (ipAddress.getAssociatedWithNetworkId() == null) {
                throw new InvalidParameterValueException("Ip address " + ipAddress + " is not assigned to the network " + network);
            }
            // Check permissions
            if (ipAddress.getSystem()) {
                // when system is enabling static NAT on system IP's (for EIP) ignore VM state
                checkIpAndUserVm(ipAddress, vm, caller, true);
            } else {
                checkIpAndUserVm(ipAddress, vm, caller, false);
            }
            //dstIp = guestNic.getIp4Address();
            if (vmGuestIp != null) {
                if (!dstIp.equals(vmGuestIp)) {
                    //check whether the secondary ip set to the vm or not
                    boolean secondaryIpSet = _networkMgr.isSecondaryIpSetForNic(guestNic.getId());
                    if (!secondaryIpSet) {
                        throw new InvalidParameterValueException("VM ip " + vmGuestIp + " address not belongs to the vm");
                    }
                    //check the ip belongs to the vm or not
                    nicSecIp = _nicSecondaryDao.findByIp4AddressAndNicId(vmGuestIp, guestNic.getId());
                    if (nicSecIp == null) {
                        throw new InvalidParameterValueException("VM ip " + vmGuestIp + " address not belongs to the vm");
                    }
                    dstIp = nicSecIp.getIp4Address();
                // Set public ip column with the vm ip
                }
            }
            // Verify ip address parameter
            // checking vm id is not sufficient, check for the vm ip
            isIpReadyForStaticNat(vmId, ipAddress, dstIp, caller, ctx.getCallingUserId());
        }
        ipAddress.setOneToOneNat(true);
        ipAddress.setAssociatedWithVmId(vmId);
        ipAddress.setVmIp(dstIp);
        if (_ipAddressDao.update(ipAddress.getId(), ipAddress)) {
            // enable static nat on the backend
            s_logger.trace("Enabling static nat for ip address " + ipAddress + " and vm id=" + vmId + " on the backend");
            if (applyStaticNatForIp(ipId, false, caller, false)) {
                // ignor unassignIPFromVpcNetwork in finally block
                performedIpAssoc = false;
                return true;
            } else {
                s_logger.warn("Failed to enable static nat rule for ip address " + ipId + " on the backend");
                ipAddress.setOneToOneNat(isOneToOneNat);
                ipAddress.setAssociatedWithVmId(associatedWithVmId);
                ipAddress.setVmIp(null);
                _ipAddressDao.update(ipAddress.getId(), ipAddress);
            }
        } else {
            s_logger.warn("Failed to update ip address " + ipAddress + " in the DB as a part of enableStaticNat");
        }
    } finally {
        if (performedIpAssoc) {
            //if the rule is the last one for the ip address assigned to VPC, unassign it from the network
            IpAddress ip = _ipAddressDao.findById(ipAddress.getId());
            _vpcMgr.unassignIPFromVpcNetwork(ip.getId(), networkId);
        }
    }
    return false;
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) Nic(com.cloud.vm.Nic) CallContext(org.apache.cloudstack.context.CallContext) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NicSecondaryIpVO(com.cloud.vm.dao.NicSecondaryIpVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Network(com.cloud.network.Network) IPAddressVO(com.cloud.network.dao.IPAddressVO) IpAddress(com.cloud.network.IpAddress)

Example 17 with UserVmVO

use of com.cloud.vm.UserVmVO in project cloudstack by apache.

the class CommandSetupHelper method createVmDataCommandForVMs.

public void createVmDataCommandForVMs(final DomainRouterVO router, final Commands cmds, final long guestNetworkId) {
    final List<UserVmVO> vms = _userVmDao.listByNetworkIdAndStates(guestNetworkId, VirtualMachine.State.Running, VirtualMachine.State.Migrating, VirtualMachine.State.Stopping);
    final DataCenterVO dc = _dcDao.findById(router.getDataCenterId());
    for (final UserVmVO vm : vms) {
        boolean createVmData = true;
        if (dc.getNetworkType() == NetworkType.Basic && router.getPodIdToDeployIn().longValue() != vm.getPodIdToDeployIn().longValue()) {
            createVmData = false;
        }
        if (createVmData) {
            final NicVO nic = _nicDao.findByNtwkIdAndInstanceId(guestNetworkId, vm.getId());
            if (nic != null) {
                s_logger.debug("Creating user data entry for vm " + vm + " on domR " + router);
                createVmDataCommand(router, vm, nic, null, cmds);
            }
        }
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) UserVmVO(com.cloud.vm.UserVmVO) NicVO(com.cloud.vm.NicVO)

Example 18 with UserVmVO

use of com.cloud.vm.UserVmVO in project cloudstack by apache.

the class CommandSetupHelper method createDhcpEntryCommandsForVMs.

public void createDhcpEntryCommandsForVMs(final DomainRouterVO router, final Commands cmds, final long guestNetworkId) {
    final List<UserVmVO> vms = _userVmDao.listByNetworkIdAndStates(guestNetworkId, VirtualMachine.State.Running, VirtualMachine.State.Migrating, VirtualMachine.State.Stopping);
    final DataCenterVO dc = _dcDao.findById(router.getDataCenterId());
    String dnsBasicZoneUpdates = _configDao.getValue(Config.DnsBasicZoneUpdates.key());
    for (final UserVmVO vm : vms) {
        if (dc.getNetworkType() == NetworkType.Basic && router.getPodIdToDeployIn().longValue() != vm.getPodIdToDeployIn().longValue() && dnsBasicZoneUpdates.equalsIgnoreCase("pod")) {
            continue;
        }
        final NicVO nic = _nicDao.findByNtwkIdAndInstanceId(guestNetworkId, vm.getId());
        if (nic != null) {
            s_logger.debug("Creating dhcp entry for vm " + vm + " on domR " + router + ".");
            createDhcpEntryCommand(router, vm, nic, cmds);
        }
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) UserVmVO(com.cloud.vm.UserVmVO) NicVO(com.cloud.vm.NicVO)

Example 19 with UserVmVO

use of com.cloud.vm.UserVmVO in project cloudstack by apache.

the class StoragePoolAutomationImpl method cancelMaintain.

@Override
public boolean cancelMaintain(DataStore store) {
    // Change the storage state back to up
    Long userId = CallContext.current().getCallingUserId();
    User user = _userDao.findById(userId);
    Account account = CallContext.current().getCallingAccount();
    StoragePoolVO poolVO = primaryDataStoreDao.findById(store.getId());
    StoragePool pool = (StoragePool) store;
    //Handeling the Zone wide and cluster wide primay storage
    List<HostVO> hosts = new ArrayList<HostVO>();
    // if the storage scope is ZONE wide, then get all the hosts for which hypervisor ZWSP created to send Modifystoragepoolcommand
    if (poolVO.getScope().equals(ScopeType.ZONE)) {
        if (HypervisorType.Any.equals(pool.getHypervisor())) {
            hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZone(pool.getDataCenterId());
        } else {
            hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(poolVO.getHypervisor(), pool.getDataCenterId());
        }
    } else {
        hosts = _resourceMgr.listHostsInClusterByStatus(pool.getClusterId(), Status.Up);
    }
    if (hosts == null || hosts.size() == 0) {
        return true;
    }
    // add heartbeat
    for (HostVO host : hosts) {
        ModifyStoragePoolCommand msPoolCmd = new ModifyStoragePoolCommand(true, pool);
        final Answer answer = agentMgr.easySend(host.getId(), msPoolCmd);
        if (answer == null || !answer.getResult()) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("ModifyStoragePool add failed due to " + ((answer == null) ? "answer null" : answer.getDetails()));
            }
        } else {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("ModifyStoragePool add secceeded");
            }
        }
    }
    // 2. Get a list of pending work for this queue
    List<StoragePoolWorkVO> pendingWork = _storagePoolWorkDao.listPendingWorkForCancelMaintenanceByPoolId(poolVO.getId());
    // 3. work through the queue
    for (StoragePoolWorkVO work : pendingWork) {
        try {
            VMInstanceVO vmInstance = vmDao.findById(work.getVmId());
            if (vmInstance == null) {
                continue;
            }
            // proxy
            if (vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy)) {
                ConsoleProxyVO consoleProxy = _consoleProxyDao.findById(vmInstance.getId());
                vmMgr.advanceStart(consoleProxy.getUuid(), null, null);
                // update work queue
                work.setStartedAfterMaintenance(true);
                _storagePoolWorkDao.update(work.getId(), work);
            }
            // if the instance is of type ssvm, call the ssvm manager
            if (vmInstance.getType().equals(VirtualMachine.Type.SecondaryStorageVm)) {
                SecondaryStorageVmVO ssVm = _secStrgDao.findById(vmInstance.getId());
                vmMgr.advanceStart(ssVm.getUuid(), null, null);
                // update work queue
                work.setStartedAfterMaintenance(true);
                _storagePoolWorkDao.update(work.getId(), work);
            }
            // manager
            if (vmInstance.getType().equals(VirtualMachine.Type.DomainRouter)) {
                DomainRouterVO domR = _domrDao.findById(vmInstance.getId());
                vmMgr.advanceStart(domR.getUuid(), null, null);
                // update work queue
                work.setStartedAfterMaintenance(true);
                _storagePoolWorkDao.update(work.getId(), work);
            }
            // if the instance is of type user vm, call the user vm manager
            if (vmInstance.getType().equals(VirtualMachine.Type.User)) {
                // don't allow to start vm that doesn't have a root volume
                if (volumeDao.findByInstanceAndType(vmInstance.getId(), Volume.Type.ROOT).isEmpty()) {
                    _storagePoolWorkDao.remove(work.getId());
                } else {
                    UserVmVO userVm = userVmDao.findById(vmInstance.getId());
                    vmMgr.advanceStart(userVm.getUuid(), null, null);
                    work.setStartedAfterMaintenance(true);
                    _storagePoolWorkDao.update(work.getId(), work);
                }
            }
        } catch (Exception e) {
            s_logger.debug("Failed start vm", e);
            throw new CloudRuntimeException(e.toString());
        }
    }
    return false;
}
Also used : Account(com.cloud.user.Account) SecondaryStorageVmVO(com.cloud.vm.SecondaryStorageVmVO) UserVmVO(com.cloud.vm.UserVmVO) User(com.cloud.user.User) ArrayList(java.util.ArrayList) VMInstanceVO(com.cloud.vm.VMInstanceVO) HostVO(com.cloud.host.HostVO) ModifyStoragePoolCommand(com.cloud.agent.api.ModifyStoragePoolCommand) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Answer(com.cloud.agent.api.Answer) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) ConsoleProxyVO(com.cloud.vm.ConsoleProxyVO) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 20 with UserVmVO

use of com.cloud.vm.UserVmVO in project cloudstack by apache.

the class VolumeApiServiceImpl method updateMissingRootDiskController.

public void updateMissingRootDiskController(final VMInstanceVO vm, final String rootVolChainInfo) {
    if (vm == null || !VirtualMachine.Type.User.equals(vm.getType()) || Strings.isNullOrEmpty(rootVolChainInfo)) {
        return;
    }
    String rootDiskController = null;
    try {
        final VirtualMachineDiskInfo infoInChain = _gson.fromJson(rootVolChainInfo, VirtualMachineDiskInfo.class);
        if (infoInChain != null) {
            rootDiskController = infoInChain.getControllerFromDeviceBusName();
        }
        final UserVmVO userVmVo = _userVmDao.findById(vm.getId());
        if ((rootDiskController != null) && (!rootDiskController.isEmpty())) {
            _userVmDao.loadDetails(userVmVo);
            _userVmMgr.persistDeviceBusInfo(userVmVo, rootDiskController);
        }
    } catch (JsonParseException e) {
        s_logger.debug("Error parsing chain info json: " + e.getMessage());
    }
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) VirtualMachineDiskInfo(org.apache.cloudstack.utils.volume.VirtualMachineDiskInfo) JsonParseException(com.google.gson.JsonParseException)

Aggregations

UserVmVO (com.cloud.vm.UserVmVO)88 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)32 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)30 Account (com.cloud.user.Account)23 ArrayList (java.util.ArrayList)21 HostVO (com.cloud.host.HostVO)14 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)13 VMSnapshotVO (com.cloud.vm.snapshot.VMSnapshotVO)13 DataCenterVO (com.cloud.dc.DataCenterVO)12 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)12 VolumeVO (com.cloud.storage.VolumeVO)10 NicVO (com.cloud.vm.NicVO)10 VMInstanceVO (com.cloud.vm.VMInstanceVO)10 ActionEvent (com.cloud.event.ActionEvent)9 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)9 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)9 DomainRouterVO (com.cloud.vm.DomainRouterVO)9 Commands (com.cloud.agent.manager.Commands)8 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)8 VirtualRouter (com.cloud.network.router.VirtualRouter)8