Search in sources :

Example 51 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class ApiResponseHelper method createUsageResponse.

@Override
public UsageRecordResponse createUsageResponse(Usage usageRecord) {
    UsageRecordResponse usageRecResponse = new UsageRecordResponse();
    Account account = ApiDBUtils.findAccountById(usageRecord.getAccountId());
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        //find the project
        Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId());
        if (project != null) {
            usageRecResponse.setProjectId(project.getUuid());
            usageRecResponse.setProjectName(project.getName());
        }
    } else {
        usageRecResponse.setAccountId(account.getUuid());
        usageRecResponse.setAccountName(account.getAccountName());
    }
    Domain domain = ApiDBUtils.findDomainById(usageRecord.getDomainId());
    if (domain != null) {
        usageRecResponse.setDomainId(domain.getUuid());
        usageRecResponse.setDomainName(domain.getName());
    }
    if (usageRecord.getZoneId() != null) {
        DataCenter zone = ApiDBUtils.findZoneById(usageRecord.getZoneId());
        if (zone != null) {
            usageRecResponse.setZoneId(zone.getUuid());
        }
    }
    usageRecResponse.setDescription(usageRecord.getDescription());
    usageRecResponse.setUsage(usageRecord.getUsageDisplay());
    usageRecResponse.setUsageType(usageRecord.getUsageType());
    if (usageRecord.getVmInstanceId() != null) {
        VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId());
        if (vm != null) {
            usageRecResponse.setVirtualMachineId(vm.getUuid());
        }
    }
    usageRecResponse.setVmName(usageRecord.getVmName());
    if (usageRecord.getTemplateId() != null) {
        VMTemplateVO template = ApiDBUtils.findTemplateById(usageRecord.getTemplateId());
        if (template != null) {
            usageRecResponse.setTemplateId(template.getUuid());
        }
    }
    if (usageRecord.getUsageType() == UsageTypes.RUNNING_VM || usageRecord.getUsageType() == UsageTypes.ALLOCATED_VM) {
        ServiceOfferingVO svcOffering = _entityMgr.findByIdIncludingRemoved(ServiceOfferingVO.class, usageRecord.getOfferingId().toString());
        //Service Offering Id
        usageRecResponse.setOfferingId(svcOffering.getUuid());
        //VM Instance ID
        VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
        if (vm != null) {
            usageRecResponse.setUsageId(vm.getUuid());
        }
        //Hypervisor Type
        usageRecResponse.setType(usageRecord.getType());
        //Dynamic compute offerings details
        usageRecResponse.setCpuNumber(usageRecord.getCpuCores());
        usageRecResponse.setCpuSpeed(usageRecord.getCpuSpeed());
        usageRecResponse.setMemory(usageRecord.getMemory());
    } else if (usageRecord.getUsageType() == UsageTypes.IP_ADDRESS) {
        //isSourceNAT
        usageRecResponse.setSourceNat((usageRecord.getType().equals("SourceNat")) ? true : false);
        //isSystem
        usageRecResponse.setSystem((usageRecord.getSize() == 1) ? true : false);
        //IP Address ID
        IPAddressVO ip = _entityMgr.findByIdIncludingRemoved(IPAddressVO.class, usageRecord.getUsageId().toString());
        if (ip != null) {
            usageRecResponse.setUsageId(ip.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_SENT || usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_RECEIVED) {
        //Device Type
        usageRecResponse.setType(usageRecord.getType());
        if (usageRecord.getType().equals("DomainRouter")) {
            //Domain Router Id
            VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
            if (vm != null) {
                usageRecResponse.setUsageId(vm.getUuid());
            }
        } else {
            //External Device Host Id
            HostVO host = _entityMgr.findByIdIncludingRemoved(HostVO.class, usageRecord.getUsageId().toString());
            if (host != null) {
                usageRecResponse.setUsageId(host.getUuid());
            }
        }
        //Network ID
        if ((usageRecord.getNetworkId() != null) && (usageRecord.getNetworkId() != 0)) {
            NetworkVO network = _entityMgr.findByIdIncludingRemoved(NetworkVO.class, usageRecord.getNetworkId().toString());
            if (network != null) {
                usageRecResponse.setNetworkId(network.getUuid());
            }
        }
    } else if (usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_WRITE || usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_WRITE) {
        //Device Type
        usageRecResponse.setType(usageRecord.getType());
        //VM Instance Id
        VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId().toString());
        if (vm != null) {
            usageRecResponse.setVirtualMachineId(vm.getUuid());
        }
        //Volume ID
        VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
        if (volume != null) {
            usageRecResponse.setUsageId(volume.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.VOLUME) {
        //Volume ID
        VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
        if (volume != null) {
            usageRecResponse.setUsageId(volume.getUuid());
        }
        //Volume Size
        usageRecResponse.setSize(usageRecord.getSize());
        //Disk Offering Id
        if (usageRecord.getOfferingId() != null) {
            DiskOfferingVO diskOff = _entityMgr.findByIdIncludingRemoved(DiskOfferingVO.class, usageRecord.getOfferingId().toString());
            usageRecResponse.setOfferingId(diskOff.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.TEMPLATE || usageRecord.getUsageType() == UsageTypes.ISO) {
        //Template/ISO ID
        VMTemplateVO tmpl = _entityMgr.findByIdIncludingRemoved(VMTemplateVO.class, usageRecord.getUsageId().toString());
        if (tmpl != null) {
            usageRecResponse.setUsageId(tmpl.getUuid());
        }
        //Template/ISO Size
        usageRecResponse.setSize(usageRecord.getSize());
        if (usageRecord.getUsageType() == UsageTypes.ISO) {
            usageRecResponse.setVirtualSize(usageRecord.getSize());
        } else {
            usageRecResponse.setVirtualSize(usageRecord.getVirtualSize());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.SNAPSHOT) {
        //Snapshot ID
        SnapshotVO snap = _entityMgr.findByIdIncludingRemoved(SnapshotVO.class, usageRecord.getUsageId().toString());
        if (snap != null) {
            usageRecResponse.setUsageId(snap.getUuid());
        }
        //Snapshot Size
        usageRecResponse.setSize(usageRecord.getSize());
    } else if (usageRecord.getUsageType() == UsageTypes.LOAD_BALANCER_POLICY) {
        //Load Balancer Policy ID
        LoadBalancerVO lb = _entityMgr.findByIdIncludingRemoved(LoadBalancerVO.class, usageRecord.getUsageId().toString());
        if (lb != null) {
            usageRecResponse.setUsageId(lb.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.PORT_FORWARDING_RULE) {
        //Port Forwarding Rule ID
        PortForwardingRuleVO pf = _entityMgr.findByIdIncludingRemoved(PortForwardingRuleVO.class, usageRecord.getUsageId().toString());
        if (pf != null) {
            usageRecResponse.setUsageId(pf.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.NETWORK_OFFERING) {
        //Network Offering Id
        NetworkOfferingVO netOff = _entityMgr.findByIdIncludingRemoved(NetworkOfferingVO.class, usageRecord.getOfferingId().toString());
        usageRecResponse.setOfferingId(netOff.getUuid());
        //is Default
        usageRecResponse.setDefault((usageRecord.getUsageId() == 1) ? true : false);
    } else if (usageRecord.getUsageType() == UsageTypes.VPN_USERS) {
        //VPN User ID
        VpnUserVO vpnUser = _entityMgr.findByIdIncludingRemoved(VpnUserVO.class, usageRecord.getUsageId().toString());
        if (vpnUser != null) {
            usageRecResponse.setUsageId(vpnUser.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.SECURITY_GROUP) {
        //Security Group Id
        SecurityGroupVO sg = _entityMgr.findByIdIncludingRemoved(SecurityGroupVO.class, usageRecord.getUsageId().toString());
        if (sg != null) {
            usageRecResponse.setUsageId(sg.getUuid());
        }
    } else if (usageRecord.getUsageType() == UsageTypes.VM_SNAPSHOT) {
        VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId().toString());
        if (vm != null) {
            usageRecResponse.setVmName(vm.getInstanceName());
            usageRecResponse.setUsageId(vm.getUuid());
        }
        usageRecResponse.setSize(usageRecord.getSize());
        if (usageRecord.getOfferingId() != null) {
            usageRecResponse.setOfferingId(usageRecord.getOfferingId().toString());
        }
    }
    if (usageRecord.getRawUsage() != null) {
        DecimalFormat decimalFormat = new DecimalFormat("###########.######");
        usageRecResponse.setRawUsage(decimalFormat.format(usageRecord.getRawUsage()));
    }
    if (usageRecord.getStartDate() != null) {
        usageRecResponse.setStartDate(getDateStringInternal(usageRecord.getStartDate()));
    }
    if (usageRecord.getEndDate() != null) {
        usageRecResponse.setEndDate(getDateStringInternal(usageRecord.getEndDate()));
    }
    return usageRecResponse;
}
Also used : UsageRecordResponse(org.apache.cloudstack.api.response.UsageRecordResponse) ProjectAccount(com.cloud.projects.ProjectAccount) UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) SecurityGroupVO(com.cloud.network.security.SecurityGroupVO) VpnUserVO(com.cloud.network.VpnUserVO) DecimalFormat(java.text.DecimalFormat) VMTemplateVO(com.cloud.storage.VMTemplateVO) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) HostVO(com.cloud.host.HostVO) Project(com.cloud.projects.Project) DataCenter(com.cloud.dc.DataCenter) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) Domain(com.cloud.domain.Domain)

Example 52 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class NetworkServiceImpl method releaseIpAddressInternal.

@DB
private boolean releaseIpAddressInternal(long ipAddressId) throws InsufficientAddressCapacityException {
    Long userId = CallContext.current().getCallingUserId();
    Account caller = CallContext.current().getCallingAccount();
    // Verify input parameters
    IPAddressVO ipVO = _ipAddressDao.findById(ipAddressId);
    if (ipVO == null) {
        throw new InvalidParameterValueException("Unable to find ip address by id");
    }
    if (ipVO.getAllocatedTime() == null) {
        s_logger.debug("Ip Address id= " + ipAddressId + " is not allocated, so do nothing.");
        return true;
    }
    // verify permissions
    if (ipVO.getAllocatedToAccountId() != null) {
        _accountMgr.checkAccess(caller, null, true, ipVO);
    }
    if (ipVO.isSourceNat()) {
        throw new IllegalArgumentException("ip address is used for source nat purposes and can not be disassociated.");
    }
    VlanVO vlan = _vlanDao.findById(ipVO.getVlanId());
    if (!vlan.getVlanType().equals(VlanType.VirtualNetwork)) {
        throw new IllegalArgumentException("only ip addresses that belong to a virtual network may be disassociated.");
    }
    // don't allow releasing system ip address
    if (ipVO.getSystem()) {
        InvalidParameterValueException ex = new InvalidParameterValueException("Can't release system IP address with specified id");
        ex.addProxyObject(ipVO.getUuid(), "systemIpAddrId");
        throw ex;
    }
    boolean success = _ipAddrMgr.disassociatePublicIpAddress(ipAddressId, userId, caller);
    if (success) {
        Long networkId = ipVO.getAssociatedWithNetworkId();
        if (networkId != null) {
            Network guestNetwork = getNetwork(networkId);
            NetworkOffering offering = _entityMgr.findById(NetworkOffering.class, guestNetwork.getNetworkOfferingId());
            Long vmId = ipVO.getAssociatedWithVmId();
            if (offering.getElasticIp() && vmId != null) {
                _rulesMgr.getSystemIpAndEnableStaticNatForVm(_userVmDao.findById(vmId), true);
                return true;
            }
        }
    } else {
        s_logger.warn("Failed to release public ip address id=" + ipAddressId);
    }
    return success;
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) NetworkOffering(com.cloud.offering.NetworkOffering) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) DB(com.cloud.utils.db.DB)

Example 53 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO 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 54 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class GlobalLoadBalancingRulesServiceImpl method applyGlobalLoadBalancerRuleConfig.

private boolean applyGlobalLoadBalancerRuleConfig(long gslbRuleId, boolean revoke) throws ResourceUnavailableException {
    GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
    assert (gslbRule != null);
    String lbMethod = gslbRule.getAlgorithm();
    String persistenceMethod = gslbRule.getPersistence();
    String serviceType = gslbRule.getServiceType();
    // each Gslb rule will have a FQDN, formed from the domain name associated with the gslb rule
    // and the deployment DNS name configured in global config parameter 'cloud.dns.name'
    String domainName = gslbRule.getGslbDomain();
    String providerDnsName = _globalConfigDao.getValue(Config.CloudDnsName.key());
    String gslbFqdn = domainName + "." + providerDnsName;
    GlobalLoadBalancerConfigCommand gslbConfigCmd = new GlobalLoadBalancerConfigCommand(gslbFqdn, lbMethod, persistenceMethod, serviceType, gslbRuleId, revoke);
    // list of the physical network participating in global load balancing
    List<Pair<Long, Long>> gslbSiteIds = new ArrayList<Pair<Long, Long>>();
    // map of the zone and info corresponding to the load balancer configured in the zone
    Map<Long, SiteLoadBalancerConfig> zoneSiteLoadbalancerMap = new HashMap<Long, SiteLoadBalancerConfig>();
    List<GlobalLoadBalancerLbRuleMapVO> gslbLbMapVos = _gslbLbMapDao.listByGslbRuleId(gslbRuleId);
    assert (gslbLbMapVos != null && !gslbLbMapVos.isEmpty());
    for (GlobalLoadBalancerLbRuleMapVO gslbLbMapVo : gslbLbMapVos) {
        // get the zone in which load balancer rule is deployed
        LoadBalancerVO loadBalancer = _lbDao.findById(gslbLbMapVo.getLoadBalancerId());
        Network network = _networkDao.findById(loadBalancer.getNetworkId());
        long dataCenterId = network.getDataCenterId();
        long physicalNetworkId = network.getPhysicalNetworkId();
        gslbSiteIds.add(new Pair<Long, Long>(dataCenterId, physicalNetworkId));
        IPAddressVO ip = _ipAddressDao.findById(loadBalancer.getSourceIpAddressId());
        SiteLoadBalancerConfig siteLb = new SiteLoadBalancerConfig(gslbLbMapVo.isRevoke(), serviceType, ip.getAddress().addr(), Integer.toString(loadBalancer.getDefaultPortStart()), dataCenterId);
        siteLb.setGslbProviderPublicIp(lookupGslbServiceProvider().getZoneGslbProviderPublicIp(dataCenterId, physicalNetworkId));
        siteLb.setGslbProviderPrivateIp(lookupGslbServiceProvider().getZoneGslbProviderPrivateIp(dataCenterId, physicalNetworkId));
        siteLb.setWeight(gslbLbMapVo.getWeight());
        zoneSiteLoadbalancerMap.put(network.getDataCenterId(), siteLb);
    }
    // to the corresponding GSLB service provider in that zone
    for (Pair<Long, Long> zoneId : gslbSiteIds) {
        List<SiteLoadBalancerConfig> slbs = new ArrayList<SiteLoadBalancerConfig>();
        // set site as 'local' for the site in that zone
        for (Pair<Long, Long> innerLoopZoneId : gslbSiteIds) {
            SiteLoadBalancerConfig siteLb = zoneSiteLoadbalancerMap.get(innerLoopZoneId.first());
            siteLb.setLocal(zoneId.first() == innerLoopZoneId.first());
            slbs.add(siteLb);
        }
        gslbConfigCmd.setSiteLoadBalancers(slbs);
        gslbConfigCmd.setForRevoke(revoke);
        // revoke GSLB configuration completely on the site GSLB provider for the sites that no longer
        // are participants of a GSLB rule
        SiteLoadBalancerConfig siteLb = zoneSiteLoadbalancerMap.get(zoneId.first());
        if (siteLb.forRevoke()) {
            gslbConfigCmd.setForRevoke(true);
        }
        try {
            lookupGslbServiceProvider().applyGlobalLoadBalancerRule(zoneId.first(), zoneId.second(), gslbConfigCmd);
        } catch (ResourceUnavailableException | NullPointerException e) {
            String msg = "Failed to configure GSLB rule in the zone " + zoneId.first() + " due to " + e.getMessage();
            s_logger.warn(msg);
            throw new CloudRuntimeException(msg);
        }
    }
    return true;
}
Also used : GlobalLoadBalancerConfigCommand(com.cloud.agent.api.routing.GlobalLoadBalancerConfigCommand) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) SiteLoadBalancerConfig(com.cloud.agent.api.routing.SiteLoadBalancerConfig) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) IPAddressVO(com.cloud.network.dao.IPAddressVO) Pair(com.cloud.utils.Pair)

Example 55 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class CommandSetupHelper method createRedundantAssociateIPCommands.

public void createRedundantAssociateIPCommands(final VirtualRouter router, final List<? extends PublicIpAddress> ips, final Commands cmds, final String ipAssocCommand, final long vmId) {
    // Ensure that in multiple vlans case we first send all ip addresses of
    // vlan1, then all ip addresses of vlan2, etc..
    final Map<String, ArrayList<PublicIpAddress>> vlanIpMap = new HashMap<String, ArrayList<PublicIpAddress>>();
    for (final PublicIpAddress ipAddress : ips) {
        final String vlanTag = ipAddress.getVlanTag();
        ArrayList<PublicIpAddress> ipList = vlanIpMap.get(vlanTag);
        if (ipList == null) {
            ipList = new ArrayList<PublicIpAddress>();
        }
        // the state
        if (ipAddress.isSourceNat() && ipAddress.getState() == IpAddress.State.Releasing) {
            ipAddress.setState(IpAddress.State.Allocated);
        }
        ipList.add(ipAddress);
        vlanIpMap.put(vlanTag, ipList);
    }
    final List<NicVO> nics = _nicDao.listByVmId(router.getId());
    String baseMac = null;
    for (final NicVO nic : nics) {
        final NetworkVO nw = _networkDao.findById(nic.getNetworkId());
        if (nw.getTrafficType() == TrafficType.Public) {
            baseMac = nic.getMacAddress();
            break;
        }
    }
    for (final Map.Entry<String, ArrayList<PublicIpAddress>> vlanAndIp : vlanIpMap.entrySet()) {
        final List<PublicIpAddress> ipAddrList = vlanAndIp.getValue();
        // Source nat ip address should always be sent first
        Collections.sort(ipAddrList, new Comparator<PublicIpAddress>() {

            @Override
            public int compare(final PublicIpAddress o1, final PublicIpAddress o2) {
                final boolean s1 = o1.isSourceNat();
                final boolean s2 = o2.isSourceNat();
                return s1 ^ s2 ? s1 ^ true ? 1 : -1 : 0;
            }
        });
        // Get network rate - required for IpAssoc
        final Integer networkRate = _networkModel.getNetworkRate(ipAddrList.get(0).getNetworkId(), router.getId());
        final Network network = _networkModel.getNetwork(ipAddrList.get(0).getNetworkId());
        final IpAddressTO[] ipsToSend = new IpAddressTO[ipAddrList.size()];
        int i = 0;
        boolean firstIP = true;
        for (final PublicIpAddress ipAddr : ipAddrList) {
            final boolean add = ipAddr.getState() == IpAddress.State.Releasing ? false : true;
            boolean sourceNat = ipAddr.isSourceNat();
            /* enable sourceNAT for the first ip of the public interface */
            if (firstIP) {
                sourceNat = true;
            }
            final String vlanId = ipAddr.getVlanTag();
            final String vlanGateway = ipAddr.getGateway();
            final String vlanNetmask = ipAddr.getNetmask();
            String vifMacAddress = null;
            // first ip of other nics
            if (router.getVpcId() != null) {
                //vifMacAddress = NetUtils.generateMacOnIncrease(baseMac, ipAddr.getVlanId());
                vifMacAddress = ipAddr.getMacAddress();
            } else {
                if (!sourceNat && ipAddr.getVlanId() != 0) {
                    vifMacAddress = NetUtils.generateMacOnIncrease(baseMac, ipAddr.getVlanId());
                } else {
                    vifMacAddress = ipAddr.getMacAddress();
                }
            }
            final IpAddressTO ip = new IpAddressTO(ipAddr.getAccountId(), ipAddr.getAddress().addr(), add, firstIP, sourceNat, vlanId, vlanGateway, vlanNetmask, vifMacAddress, networkRate, ipAddr.isOneToOneNat());
            ip.setTrafficType(network.getTrafficType());
            ip.setNetworkName(_networkModel.getNetworkTag(router.getHypervisorType(), network));
            ipsToSend[i++] = ip;
            /*
                 * send the firstIP = true for the first Add, this is to create
                 * primary on interface
                 */
            if (!firstIP || add) {
                firstIP = false;
            }
        }
        Long associatedWithNetworkId = ipAddrList.get(0).getAssociatedWithNetworkId();
        if (associatedWithNetworkId == null || associatedWithNetworkId == 0) {
            associatedWithNetworkId = ipAddrList.get(0).getNetworkId();
        }
        // for network if the ips does not have any rules, then only last ip
        List<IPAddressVO> userIps = _ipAddressDao.listByAssociatedNetwork(associatedWithNetworkId, null);
        int ipsWithrules = 0;
        int ipsStaticNat = 0;
        for (IPAddressVO ip : userIps) {
            if (_rulesDao.countRulesByIpIdAndState(ip.getId(), FirewallRule.State.Active) > 0) {
                ipsWithrules++;
            }
            // 1 static nat rule add
            if (ip.isOneToOneNat() && ip.getRuleState() == null) {
                ipsStaticNat++;
            }
        }
        final IpAssocCommand cmd = new IpAssocCommand(ipsToSend);
        cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, _routerControlHelper.getRouterControlIp(router.getId()));
        cmd.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, _routerControlHelper.getRouterIpInNetwork(associatedWithNetworkId, router.getId()));
        cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
        final DataCenterVO dcVo = _dcDao.findById(router.getDataCenterId());
        cmd.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, dcVo.getNetworkType().toString());
        // if there is 1 static nat then it will be checked for remove at the resource
        if (ipsWithrules == 0 && ipsStaticNat == 0) {
            // there is only one ip address for the network.
            cmd.setAccessDetail(NetworkElementCommand.NETWORK_PUB_LAST_IP, "true");
        } else {
            cmd.setAccessDetail(NetworkElementCommand.NETWORK_PUB_LAST_IP, "false");
        }
        cmds.addCommand(ipAssocCommand, cmd);
    }
}
Also used : IpAddressTO(com.cloud.agent.api.to.IpAddressTO) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PublicIpAddress(com.cloud.network.PublicIpAddress) Network(com.cloud.network.Network) IpAssocCommand(com.cloud.agent.api.routing.IpAssocCommand) NicVO(com.cloud.vm.NicVO) DataCenterVO(com.cloud.dc.DataCenterVO) NetworkVO(com.cloud.network.dao.NetworkVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

IPAddressVO (com.cloud.network.dao.IPAddressVO)109 ArrayList (java.util.ArrayList)43 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)42 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)39 Account (com.cloud.user.Account)37 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)32 DB (com.cloud.utils.db.DB)28 TransactionStatus (com.cloud.utils.db.TransactionStatus)26 Network (com.cloud.network.Network)25 PublicIp (com.cloud.network.addr.PublicIp)22 DataCenter (com.cloud.dc.DataCenter)17 VlanVO (com.cloud.dc.VlanVO)16 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)16 List (java.util.List)15 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)14 Ip (com.cloud.utils.net.Ip)14 NetworkOffering (com.cloud.offering.NetworkOffering)13 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)13 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)12 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)11