Search in sources :

Example 1 with NicSecondaryIpVO

use of com.cloud.vm.dao.NicSecondaryIpVO in project cloudstack by apache.

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, String requestedIp) throws InsufficientAddressCapacityException {
    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");
    }
    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);
    Network network = _networksDao.findById(networkId);
    if (network == null) {
        throw new InvalidParameterValueException("Invalid network id is given");
    }
    int maxAllowedIpsPerNic = NumbersUtil.parseInt(_configDao.getValue(Config.MaxNumberOfSecondaryIPsPerNIC.key()), 10);
    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 (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;
        DataCenter dc = _dcDao.findById(network.getDataCenterId());
        if (dc.getNetworkType() == NetworkType.Basic) {
            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 (InsufficientAddressCapacityException e) {
            s_logger.error("Allocating ip to guest nic " + nicId + " failed");
            return null;
        }
    } 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 secodary ip
        final String addrFinal = ipaddr;
        long id = Transaction.execute(new TransactionCallback<Long>() {

            @Override
            public Long doInTransaction(TransactionStatus status) {
                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 ...");
                Long vmId = nicVO.getInstanceId();
                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) 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.exception.InvalidParameterValueException) NicVO(com.cloud.vm.NicVO) VirtualMachine(com.cloud.vm.VirtualMachine) ActionEvent(com.cloud.event.ActionEvent)

Example 2 with NicSecondaryIpVO

use of com.cloud.vm.dao.NicSecondaryIpVO in project cloudstack by apache.

the class UserVmJoinDaoImpl method setUserVmResponse.

/**
 * The resulting Response attempts to be in line with what is returned from
 * @see com.cloud.api.ApiResponseHelper#createNicResponse(Nic)
 */
@Override
public UserVmResponse setUserVmResponse(ResponseView view, UserVmResponse userVmData, UserVmJoinVO uvo) {
    Long securityGroupId = uvo.getSecurityGroupId();
    if (securityGroupId != null && securityGroupId.longValue() != 0) {
        SecurityGroupResponse resp = new SecurityGroupResponse();
        resp.setId(uvo.getSecurityGroupUuid());
        resp.setName(uvo.getSecurityGroupName());
        resp.setDescription(uvo.getSecurityGroupDescription());
        resp.setObjectName("securitygroup");
        if (uvo.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) {
            resp.setProjectId(uvo.getProjectUuid());
            resp.setProjectName(uvo.getProjectName());
        } else {
            resp.setAccountName(uvo.getAccountName());
        }
        userVmData.addSecurityGroup(resp);
    }
    long nic_id = uvo.getNicId();
    if (nic_id > 0) {
        NicResponse nicResponse = new NicResponse();
        // The numbered comments are to keep track of the data returned from here and ApiResponseHelper.createNicResponse()
        // the data can't be identical but some tidying up/unifying might be possible
        /*1: nicUuid*/
        nicResponse.setId(uvo.getNicUuid());
        /*2: networkUuid*/
        nicResponse.setNetworkid(uvo.getNetworkUuid());
        if (uvo.getTrafficType() != null) {
            /*4: trafficType*/
            nicResponse.setTrafficType(uvo.getTrafficType().toString());
        }
        if (uvo.getGuestType() != null) {
            /*5: guestType*/
            nicResponse.setType(uvo.getGuestType().toString());
        }
        /*6: ipAddress*/
        nicResponse.setIpaddress(uvo.getIpAddress());
        /*7: gateway*/
        nicResponse.setGateway(uvo.getGateway());
        /*8: netmask*/
        nicResponse.setNetmask(uvo.getNetmask());
        /*9: networkName*/
        nicResponse.setNetworkName(uvo.getNetworkName());
        /*10: macAddress*/
        nicResponse.setMacAddress(uvo.getMacAddress());
        /*11: IPv6Address*/
        nicResponse.setIp6Address(uvo.getIp6Address());
        /*12: IPv6Gateway*/
        nicResponse.setIp6Gateway(uvo.getIp6Gateway());
        /*13: IPv6Cidr*/
        nicResponse.setIp6Cidr(uvo.getIp6Cidr());
        /*15: broadcastURI*/
        if (uvo.getBroadcastUri() != null) {
            nicResponse.setBroadcastUri(uvo.getBroadcastUri().toString());
        }
        /*16: isolationURI*/
        if (uvo.getIsolationUri() != null) {
            nicResponse.setIsolationUri(uvo.getIsolationUri().toString());
        }
        /*17: default*/
        nicResponse.setIsDefault(uvo.isDefaultNic());
        nicResponse.setDeviceId(String.valueOf(uvo.getNicDeviceId()));
        List<NicSecondaryIpVO> secondaryIps = ApiDBUtils.findNicSecondaryIps(uvo.getNicId());
        if (secondaryIps != null) {
            List<NicSecondaryIpResponse> ipList = new ArrayList<NicSecondaryIpResponse>();
            for (NicSecondaryIpVO ip : secondaryIps) {
                NicSecondaryIpResponse ipRes = new NicSecondaryIpResponse();
                ipRes.setId(ip.getUuid());
                ApiResponseHelper.setResponseIpAddress(ip, ipRes);
                ipList.add(ipRes);
            }
            nicResponse.setSecondaryIps(ipList);
        }
        /* 18: extra dhcp options */
        nicResponse.setObjectName("nic");
        List<NicExtraDhcpOptionResponse> nicExtraDhcpOptionResponses = _nicExtraDhcpOptionDao.listByNicId(nic_id).stream().map(vo -> new NicExtraDhcpOptionResponse(Dhcp.DhcpOptionCode.valueOfInt(vo.getCode()).getName(), vo.getCode(), vo.getValue())).collect(Collectors.toList());
        nicResponse.setExtraDhcpOptions(nicExtraDhcpOptionResponses);
        userVmData.addNic(nicResponse);
    }
    long tag_id = uvo.getTagId();
    if (tag_id > 0 && !userVmData.containTag(tag_id)) {
        addTagInformation(uvo, userVmData);
    }
    if (userVmData.hasAnnotation() == null) {
        userVmData.setHasAnnotation(annotationDao.hasAnnotations(uvo.getUuid(), AnnotationService.EntityType.VM.name(), _accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())));
    }
    Long affinityGroupId = uvo.getAffinityGroupId();
    if (affinityGroupId != null && affinityGroupId.longValue() != 0) {
        AffinityGroupResponse resp = new AffinityGroupResponse();
        resp.setId(uvo.getAffinityGroupUuid());
        resp.setName(uvo.getAffinityGroupName());
        resp.setDescription(uvo.getAffinityGroupDescription());
        resp.setObjectName("affinitygroup");
        resp.setAccountName(uvo.getAccountName());
        userVmData.addAffinityGroup(resp);
    }
    return userVmData;
}
Also used : UserVmManager(com.cloud.vm.UserVmManager) AnnotationDao(org.apache.cloudstack.annotation.dao.AnnotationDao) UserStatisticsDao(com.cloud.user.dao.UserStatisticsDao) UserVmJoinVO(com.cloud.api.query.vo.UserVmJoinVO) Logger(org.apache.log4j.Logger) Map(java.util.Map) NicExtraDhcpOptionDao(com.cloud.vm.dao.NicExtraDhcpOptionDao) EnumSet(java.util.EnumSet) CallContext(org.apache.cloudstack.context.CallContext) State(com.cloud.vm.VirtualMachine.State) Set(java.util.Set) ApiDBUtils(com.cloud.api.ApiDBUtils) Account(com.cloud.user.Account) QueryService(org.apache.cloudstack.query.QueryService) Collectors(java.util.stream.Collectors) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) List(java.util.List) NicExtraDhcpOptionResponse(org.apache.cloudstack.api.response.NicExtraDhcpOptionResponse) NicResponse(org.apache.cloudstack.api.response.NicResponse) GuestOS(com.cloud.storage.GuestOS) ResponseView(org.apache.cloudstack.api.ResponseObject.ResponseView) SearchBuilder(com.cloud.utils.db.SearchBuilder) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ServiceOfferingDetailsVO(com.cloud.service.ServiceOfferingDetailsVO) UserDao(com.cloud.user.dao.UserDao) SearchCriteria(com.cloud.utils.db.SearchCriteria) VMDetails(org.apache.cloudstack.api.ApiConstants.VMDetails) User(com.cloud.user.User) UserVmDetailsDao(com.cloud.vm.dao.UserVmDetailsDao) UserVmDetailVO(com.cloud.vm.UserVmDetailVO) VmStats(com.cloud.vm.VmStats) AffinityGroupResponse(org.apache.cloudstack.affinity.AffinityGroupResponse) Hashtable(java.util.Hashtable) Op(com.cloud.utils.db.SearchCriteria.Op) Dhcp(com.cloud.utils.net.Dhcp) UserVmResponse(org.apache.cloudstack.api.response.UserVmResponse) UserVm(com.cloud.uservm.UserVm) ApiResponseHelper(com.cloud.api.ApiResponseHelper) GPU(com.cloud.gpu.GPU) AnnotationService(org.apache.cloudstack.annotation.AnnotationService) DecimalFormat(java.text.DecimalFormat) ApiConstants(org.apache.cloudstack.api.ApiConstants) NicSecondaryIpResponse(org.apache.cloudstack.api.response.NicSecondaryIpResponse) Component(org.springframework.stereotype.Component) AccountManager(com.cloud.user.AccountManager) SecurityGroupResponse(org.apache.cloudstack.api.response.SecurityGroupResponse) ConfigurationDao(org.apache.cloudstack.framework.config.dao.ConfigurationDao) UserStatisticsVO(com.cloud.user.UserStatisticsVO) NicSecondaryIpVO(com.cloud.vm.dao.NicSecondaryIpVO) NicExtraDhcpOptionResponse(org.apache.cloudstack.api.response.NicExtraDhcpOptionResponse) ArrayList(java.util.ArrayList) SecurityGroupResponse(org.apache.cloudstack.api.response.SecurityGroupResponse) NicSecondaryIpResponse(org.apache.cloudstack.api.response.NicSecondaryIpResponse) NicSecondaryIpVO(com.cloud.vm.dao.NicSecondaryIpVO) AffinityGroupResponse(org.apache.cloudstack.affinity.AffinityGroupResponse) NicResponse(org.apache.cloudstack.api.response.NicResponse)

Example 3 with NicSecondaryIpVO

use of com.cloud.vm.dao.NicSecondaryIpVO 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);
                        performedIpAssoc = true;
                    } 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)) {
                applyUserDataIfNeeded(vmId, network, guestNic);
                // 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) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) 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 4 with NicSecondaryIpVO

use of com.cloud.vm.dao.NicSecondaryIpVO in project cloudstack by apache.

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(long ipAddressId) {
    Account caller = CallContext.current().getCallingAccount();
    boolean success = false;
    // Verify input parameters
    NicSecondaryIpVO secIpVO = _nicSecondaryIpDao.findById(ipAddressId);
    if (secIpVO == null) {
        throw new InvalidParameterValueException("Unable to find secondary ip address by id");
    }
    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);
    Network network = _networksDao.findById(secIpVO.getNetworkId());
    if (network == null) {
        throw new InvalidParameterValueException("Invalid network id is given");
    }
    // Validate network offering
    NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(network.getNetworkOfferingId());
    Long nicId = secIpVO.getNicId();
    s_logger.debug("ip id = " + ipAddressId + " nic id = " + nicId);
    // check is this the last secondary ip for NIC
    List<NicSecondaryIpVO> ipList = _nicSecondaryIpDao.listByNicId(nicId);
    boolean lastIp = false;
    if (ipList.size() == 1) {
        // this is the last secondary ip to nic
        lastIp = true;
    }
    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
        String secondaryIp = secIpVO.getIp4Address();
        List<FirewallRuleVO> fwRulesList = _firewallDao.listByNetworkAndPurpose(network.getId(), Purpose.PortForwarding);
        if (fwRulesList.size() != 0) {
            for (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
        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 (_loadBalancerDao.isLoadBalancerRulesMappedToVmGuestIp(vm.getId(), secondaryIp, network.getId())) {
            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(TransactionStatus status) {
                    _ipAddrMgr.markIpAsUnavailable(ip.getId());
                    _ipAddressDao.unassignIpAddress(ip.getId());
                }
            });
        }
    } else {
        throw new InvalidParameterValueException("Not supported for this network now");
    }
    success = removeNicSecondaryIP(secIpVO, lastIp);
    return success;
}
Also used : Account(com.cloud.user.Account) 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.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 5 with NicSecondaryIpVO

use of com.cloud.vm.dao.NicSecondaryIpVO in project cloudstack by apache.

the class ApiResponseHelper method showVmInfoForSharedNetworks.

private void showVmInfoForSharedNetworks(boolean forVirtualNetworks, IpAddress ipAddr, IPAddressResponse ipResponse) {
    if (!forVirtualNetworks) {
        NicVO nic = ApiDBUtils.findByIp4AddressAndNetworkId(ipAddr.getAddress().toString(), ipAddr.getNetworkId());
        if (nic == null) {
            // find in nic_secondary_ips, user vm only
            NicSecondaryIpVO secondaryIp = ApiDBUtils.findSecondaryIpByIp4AddressAndNetworkId(ipAddr.getAddress().toString(), ipAddr.getNetworkId());
            if (secondaryIp != null) {
                UserVm vm = ApiDBUtils.findUserVmById(secondaryIp.getVmId());
                if (vm != null) {
                    ipResponse.setVirtualMachineId(vm.getUuid());
                    ipResponse.setVirtualMachineName(vm.getHostName());
                    if (vm.getDisplayName() != null) {
                        ipResponse.setVirtualMachineDisplayName(vm.getDisplayName());
                    } else {
                        ipResponse.setVirtualMachineDisplayName(vm.getHostName());
                    }
                }
            }
        } else if (nic.getVmType() == VirtualMachine.Type.User) {
            UserVm vm = ApiDBUtils.findUserVmById(nic.getInstanceId());
            if (vm != null) {
                ipResponse.setVirtualMachineId(vm.getUuid());
                ipResponse.setVirtualMachineName(vm.getHostName());
                if (vm.getDisplayName() != null) {
                    ipResponse.setVirtualMachineDisplayName(vm.getDisplayName());
                } else {
                    ipResponse.setVirtualMachineDisplayName(vm.getHostName());
                }
            }
        } else if (nic.getVmType() == VirtualMachine.Type.DomainRouter) {
            ipResponse.setIsSystem(true);
        }
    }
}
Also used : NicSecondaryIpVO(com.cloud.vm.dao.NicSecondaryIpVO) UserVm(com.cloud.uservm.UserVm) NicVO(com.cloud.vm.NicVO)

Aggregations

NicSecondaryIpVO (com.cloud.vm.dao.NicSecondaryIpVO)18 Account (com.cloud.user.Account)11 VirtualMachine (com.cloud.vm.VirtualMachine)7 DataCenter (com.cloud.dc.DataCenter)6 IPAddressVO (com.cloud.network.dao.IPAddressVO)6 NicVO (com.cloud.vm.NicVO)6 ArrayList (java.util.ArrayList)6 ActionEvent (com.cloud.event.ActionEvent)5 User (com.cloud.user.User)5 TransactionStatus (com.cloud.utils.db.TransactionStatus)5 VMInstanceVO (com.cloud.vm.VMInstanceVO)5 ResourceTagJoinVO (com.cloud.api.query.vo.ResourceTagJoinVO)4 UserVmJoinVO (com.cloud.api.query.vo.UserVmJoinVO)4 DiskOfferingVO (com.cloud.storage.DiskOfferingVO)4 AccountManager (com.cloud.user.AccountManager)4 SearchBuilder (com.cloud.utils.db.SearchBuilder)4 SearchCriteria (com.cloud.utils.db.SearchCriteria)4 AffinityGroupResponse (com.cloud.affinity.AffinityGroupResponse)3 NicResponse (com.cloud.api.response.NicResponse)3 NicSecondaryIpResponse (com.cloud.api.response.NicSecondaryIpResponse)3