Search in sources :

Example 61 with DataCenter

use of com.cloud.dc.DataCenter in project cloudstack by apache.

the class NetworkServiceImpl method allocatePortableIP.

@Override
@ActionEvent(eventType = EventTypes.EVENT_PORTABLE_IP_ASSIGN, eventDescription = "allocating portable public Ip", create = true)
public IpAddress allocatePortableIP(Account ipOwner, int regionId, Long zoneId, Long networkId, Long vpcId) throws ResourceAllocationException, InsufficientAddressCapacityException, ConcurrentOperationException {
    Account caller = CallContext.current().getCallingAccount();
    long callerUserId = CallContext.current().getCallingUserId();
    DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
    if ((networkId == null && vpcId == null) || (networkId != null && vpcId != null)) {
        throw new InvalidParameterValueException("One of Network id or VPC is should be passed");
    }
    if (networkId != null) {
        Network network = _networksDao.findById(networkId);
        if (network == null) {
            throw new InvalidParameterValueException("Invalid network id is given");
        }
        if (network.getGuestType() == Network.GuestType.Shared) {
            if (zone == null) {
                throw new InvalidParameterValueException("Invalid zone Id is given");
            }
            // if shared network in the advanced zone, then check the caller against the network for 'AccessType.UseNetwork'
            if (zone.getNetworkType() == NetworkType.Advanced) {
                if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) {
                    _accountMgr.checkAccess(caller, AccessType.UseEntry, false, network);
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("Associate IP address called by the user " + callerUserId + " account " + ipOwner.getId());
                    }
                    return _ipAddrMgr.allocatePortableIp(ipOwner, caller, zoneId, networkId, null);
                } else {
                    throw new InvalidParameterValueException("Associate IP address can only be called on the shared networks in the advanced zone" + " with Firewall/Source Nat/Static Nat/Port Forwarding/Load balancing services enabled");
                }
            }
        }
    }
    if (vpcId != null) {
        Vpc vpc = _vpcDao.findById(vpcId);
        if (vpc == null) {
            throw new InvalidParameterValueException("Invalid vpc id is given");
        }
    }
    _accountMgr.checkAccess(caller, null, false, ipOwner);
    return _ipAddrMgr.allocatePortableIp(ipOwner, caller, zoneId, null, null);
}
Also used : Account(com.cloud.user.Account) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Vpc(com.cloud.network.vpc.Vpc) ActionEvent(com.cloud.event.ActionEvent)

Example 62 with DataCenter

use of com.cloud.dc.DataCenter 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 63 with DataCenter

use of com.cloud.dc.DataCenter in project cloudstack by apache.

the class NetworkServiceImpl method updatePhysicalNetwork.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_UPDATE, eventDescription = "updating physical network", async = true)
public PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List<String> tags, String newVnetRange, String state) {
    // verify input parameters
    PhysicalNetworkVO network = _physicalNetworkDao.findById(id);
    if (network == null) {
        InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system");
        ex.addProxyObject(id.toString(), "physicalNetworkId");
        throw ex;
    }
    // if zone is of Basic type, don't allow to add vnet range
    DataCenter zone = _dcDao.findById(network.getDataCenterId());
    if (zone == null) {
        InvalidParameterValueException ex = new InvalidParameterValueException("Zone with id=" + network.getDataCenterId() + " doesn't exist in the system");
        ex.addProxyObject(String.valueOf(network.getDataCenterId()), "dataCenterId");
        throw ex;
    }
    if (newVnetRange != null) {
        if (zone.getNetworkType() == NetworkType.Basic || (zone.getNetworkType() == NetworkType.Advanced && zone.isSecurityGroupEnabled())) {
            throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zone.getNetworkType() + " network, Security Group enabled: " + zone.isSecurityGroupEnabled());
        }
    }
    if (tags != null && tags.size() > 1) {
        throw new InvalidParameterException("Unable to support more than one tag on network yet");
    }
    PhysicalNetwork.State networkState = null;
    if (state != null && !state.isEmpty()) {
        try {
            networkState = PhysicalNetwork.State.valueOf(state);
        } catch (IllegalArgumentException ex) {
            throw new InvalidParameterValueException("Unable to resolve state '" + state + "' to a supported value {Enabled or Disabled}");
        }
    }
    if (state != null) {
        network.setState(networkState);
    }
    if (tags != null) {
        network.setTags(tags);
    }
    if (networkSpeed != null) {
        network.setSpeed(networkSpeed);
    }
    if (newVnetRange != null) {
        String[] listOfRanges = newVnetRange.split(",");
        addOrRemoveVnets(listOfRanges, network);
    }
    _physicalNetworkDao.update(id, network);
    return network;
}
Also used : InvalidParameterException(java.security.InvalidParameterException) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 64 with DataCenter

use of com.cloud.dc.DataCenter in project cloudstack by apache.

the class AutoScaleManagerImpl method createNewVM.

private long createNewVM(AutoScaleVmGroupVO asGroup) {
    AutoScaleVmProfileVO profileVo = _autoScaleVmProfileDao.findById(asGroup.getProfileId());
    long templateId = profileVo.getTemplateId();
    long serviceOfferingId = profileVo.getServiceOfferingId();
    if (templateId == -1) {
        return -1;
    }
    // create new VM into DB
    try {
        //Verify that all objects exist before passing them to the service
        Account owner = _accountService.getActiveAccountById(profileVo.getAccountId());
        DataCenter zone = _entityMgr.findById(DataCenter.class, profileVo.getZoneId());
        if (zone == null) {
            throw new InvalidParameterValueException("Unable to find zone by id=" + profileVo.getZoneId());
        }
        ServiceOffering serviceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId);
        if (serviceOffering == null) {
            throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId);
        }
        VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, templateId);
        // Make sure a valid template ID was specified
        if (template == null) {
            throw new InvalidParameterValueException("Unable to use template " + templateId);
        }
        if (!zone.isLocalStorageEnabled()) {
            if (serviceOffering.getUseLocalStorage()) {
                throw new InvalidParameterValueException("Zone is not configured to use local storage but service offering " + serviceOffering.getName() + " uses it");
            }
        }
        UserVm vm = null;
        IpAddresses addrs = new IpAddresses(null, null);
        if (zone.getNetworkType() == NetworkType.Basic) {
            vm = _userVmService.createBasicSecurityGroupVirtualMachine(zone, serviceOffering, template, null, owner, "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), null, null, null, HypervisorType.XenServer, HTTPMethod.GET, null, null, null, null, true, null, null, null, null);
        } else {
            if (zone.isSecurityGroupEnabled()) {
                vm = _userVmService.createAdvancedSecurityGroupVirtualMachine(zone, serviceOffering, template, null, null, owner, "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), null, null, null, HypervisorType.XenServer, HTTPMethod.GET, null, null, null, null, true, null, null, null, null);
            } else {
                vm = _userVmService.createAdvancedVirtualMachine(zone, serviceOffering, template, null, owner, "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), "autoScaleVm-" + asGroup.getId() + "-" + getCurrentTimeStampString(), null, null, null, HypervisorType.XenServer, HTTPMethod.GET, null, null, null, addrs, true, null, null, null, null);
            }
        }
        if (vm != null) {
            return vm.getId();
        } else {
            return -1;
        }
    } catch (InsufficientCapacityException ex) {
        s_logger.info(ex);
        s_logger.trace(ex.getMessage(), ex);
        throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage());
    } catch (ResourceUnavailableException ex) {
        s_logger.warn("Exception: ", ex);
        throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage());
    } catch (ConcurrentOperationException ex) {
        s_logger.warn("Exception: ", ex);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
    } catch (ResourceAllocationException ex) {
        s_logger.warn("Exception: ", ex);
        throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage());
    }
}
Also used : Account(com.cloud.user.Account) VirtualMachineTemplate(com.cloud.template.VirtualMachineTemplate) ServiceOffering(com.cloud.offering.ServiceOffering) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) IpAddresses(com.cloud.network.Network.IpAddresses) UserVm(com.cloud.uservm.UserVm) DataCenter(com.cloud.dc.DataCenter) ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException)

Example 65 with DataCenter

use of com.cloud.dc.DataCenter in project CloudStack-archive by CloudStack-extras.

the class AssociateIPAddrCmd method getNetworkId.

public Long getNetworkId() {
    if (networkId != null) {
        return networkId;
    }
    Long zoneId = getZoneId();
    if (zoneId == null) {
        throw new InvalidParameterValueException("Either networkId or zoneId has to be specified");
    }
    DataCenter zone = _configService.getZone(zoneId);
    if (zone.getNetworkType() == NetworkType.Advanced) {
        List<? extends Network> networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), _accountService.getAccount(getEntityOwnerId()));
        if (networks.size() == 0) {
            String domain = _domainService.getDomain(getDomainId()).getName();
            throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + " doesn't have virtual networks in zone=" + zone.getName());
        }
        if (networks.size() < 1) {
            throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone");
        } else if (networks.size() > 1) {
            throw new InvalidParameterValueException("Account has more than one Isolated network in the zone");
        }
        return networks.get(0).getId();
    } else {
        Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId);
        if (defaultGuestNetwork == null) {
            throw new InvalidParameterValueException("Unable to find a default Guest network for account " + getAccountName() + " in domain id=" + getDomainId());
        } else {
            return defaultGuestNetwork.getId();
        }
    }
}
Also used : DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Network(com.cloud.network.Network)

Aggregations

DataCenter (com.cloud.dc.DataCenter)144 Account (com.cloud.user.Account)50 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)37 NetworkVO (com.cloud.network.dao.NetworkVO)33 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)32 Network (com.cloud.network.Network)30 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)27 ArrayList (java.util.ArrayList)27 DeployDestination (com.cloud.deploy.DeployDestination)25 NetworkOffering (com.cloud.offering.NetworkOffering)23 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)17 IPAddressVO (com.cloud.network.dao.IPAddressVO)17 DB (com.cloud.utils.db.DB)17 Domain (com.cloud.domain.Domain)16 ReservationContext (com.cloud.vm.ReservationContext)16 HostVO (com.cloud.host.HostVO)15 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)13 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)13 PhysicalNetwork (com.cloud.network.PhysicalNetwork)11 ServiceOffering (com.cloud.offering.ServiceOffering)11