Search in sources :

Example 86 with ActionEvent

use of com.cloud.event.ActionEvent 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 87 with ActionEvent

use of com.cloud.event.ActionEvent 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 88 with ActionEvent

use of com.cloud.event.ActionEvent in project cloudstack by apache.

the class AutoScaleManagerImpl method createAutoScaleVmGroup.

@Override
@ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_CREATE, eventDescription = "creating autoscale vm group", create = true)
public AutoScaleVmGroup createAutoScaleVmGroup(CreateAutoScaleVmGroupCmd cmd) {
    int minMembers = cmd.getMinMembers();
    int maxMembers = cmd.getMaxMembers();
    Integer interval = cmd.getInterval();
    Boolean forDisplay = cmd.getDisplay();
    if (interval == null) {
        interval = NetUtils.DEFAULT_AUTOSCALE_POLICY_INTERVAL_TIME;
    }
    LoadBalancerVO loadBalancer = getEntityInDatabase(CallContext.current().getCallingAccount(), ApiConstants.LBID, cmd.getLbRuleId(), _lbDao);
    Long zoneId = _ipAddressDao.findById(loadBalancer.getSourceIpAddressId()).getDataCenterId();
    if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancer.getId())) {
        throw new InvalidParameterValueException("an AutoScaleVmGroup is already attached to the lb rule, the existing vm group has to be first deleted");
    }
    if (_lb2VmMapDao.isVmAttachedToLoadBalancer(loadBalancer.getId())) {
        throw new InvalidParameterValueException("there are Vms already bound to the specified LoadBalancing Rule. User bound Vms and AutoScaled Vm Group cannot co-exist on a Load Balancing Rule");
    }
    AutoScaleVmGroupVO vmGroupVO = new AutoScaleVmGroupVO(cmd.getLbRuleId(), zoneId, loadBalancer.getDomainId(), loadBalancer.getAccountId(), minMembers, maxMembers, loadBalancer.getDefaultPortStart(), interval, null, cmd.getProfileId(), AutoScaleVmGroup.State_New);
    if (forDisplay != null) {
        vmGroupVO.setDisplay(forDisplay);
    }
    vmGroupVO = checkValidityAndPersist(vmGroupVO, cmd.getScaleUpPolicyIds(), cmd.getScaleDownPolicyIds());
    s_logger.info("Successfully created Autoscale Vm Group with Id: " + vmGroupVO.getId());
    return vmGroupVO;
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ActionEvent(com.cloud.event.ActionEvent)

Example 89 with ActionEvent

use of com.cloud.event.ActionEvent in project cloudstack by apache.

the class NetworkServiceImpl method deleteNetwork.

@Override
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_DELETE, eventDescription = "deleting network", async = true)
public boolean deleteNetwork(long networkId, boolean forced) {
    Account caller = CallContext.current().getCallingAccount();
    // Verify network id
    NetworkVO network = _networksDao.findById(networkId);
    if (network == null) {
        // see NetworkVO.java
        InvalidParameterValueException ex = new InvalidParameterValueException("unable to find network with specified id");
        ex.addProxyObject(String.valueOf(networkId), "networkId");
        throw ex;
    }
    // don't allow to delete system network
    if (isNetworkSystem(network)) {
        InvalidParameterValueException ex = new InvalidParameterValueException("Network with specified id is system and can't be removed");
        ex.addProxyObject(network.getUuid(), "networkId");
        throw ex;
    }
    Account owner = _accountMgr.getAccount(network.getAccountId());
    // Only Admin can delete Shared networks
    if (network.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getId())) {
        throw new InvalidParameterValueException("Only Admins can delete network with guest type " + GuestType.Shared);
    }
    // Perform permission check
    _accountMgr.checkAccess(caller, null, true, network);
    if (forced && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new InvalidParameterValueException("Delete network with 'forced' option can only be called by root admins");
    }
    User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
    ReservationContext context = new ReservationContextImpl(null, null, callerUser, owner);
    return _networkMgr.destroyNetwork(networkId, context, forced);
}
Also used : Account(com.cloud.user.Account) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) User(com.cloud.user.User) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext) ActionEvent(com.cloud.event.ActionEvent)

Example 90 with ActionEvent

use of com.cloud.event.ActionEvent in project cloudstack by apache.

the class NetworkServiceImpl method dedicateGuestVlanRange.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_GUEST_VLAN_RANGE_DEDICATE, eventDescription = "dedicating guest vlan range", async = false)
public GuestVlan dedicateGuestVlanRange(DedicateGuestVlanRangeCmd cmd) {
    String vlan = cmd.getVlan();
    String accountName = cmd.getAccountName();
    Long domainId = cmd.getDomainId();
    Long physicalNetworkId = cmd.getPhysicalNetworkId();
    Long projectId = cmd.getProjectId();
    int startVlan, endVlan;
    String updatedVlanRange = null;
    long guestVlanMapId = 0;
    long guestVlanMapAccountId = 0;
    long vlanOwnerId = 0;
    // Verify account is valid
    Account vlanOwner = null;
    if (projectId != null) {
        if (accountName != null) {
            throw new InvalidParameterValueException("accountName and projectId are mutually exclusive");
        }
        Project project = _projectMgr.getProject(projectId);
        if (project == null) {
            throw new InvalidParameterValueException("Unable to find project by id " + projectId);
        }
        vlanOwner = _accountMgr.getAccount(project.getProjectAccountId());
    }
    if ((accountName != null) && (domainId != null)) {
        vlanOwner = _accountDao.findActiveAccount(accountName, domainId);
    }
    if (vlanOwner == null) {
        throw new InvalidParameterValueException("Unable to find account by name " + accountName);
    }
    vlanOwnerId = vlanOwner.getAccountId();
    // Verify physical network isolation type is VLAN
    PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
    if (physicalNetwork == null) {
        throw new InvalidParameterValueException("Unable to find physical network by id " + physicalNetworkId);
    } else if (!physicalNetwork.getIsolationMethods().isEmpty() && !physicalNetwork.getIsolationMethods().contains("VLAN")) {
        throw new InvalidParameterValueException("Cannot dedicate guest vlan range. " + "Physical isolation type of network " + physicalNetworkId + " is not VLAN");
    }
    // Get the start and end vlan
    String[] vlanRange = vlan.split("-");
    if (vlanRange.length != 2) {
        throw new InvalidParameterValueException("Invalid format for parameter value vlan " + vlan + " .Vlan should be specified as 'startvlan-endvlan'");
    }
    try {
        startVlan = Integer.parseInt(vlanRange[0]);
        endVlan = Integer.parseInt(vlanRange[1]);
    } catch (NumberFormatException e) {
        s_logger.warn("Unable to parse guest vlan range:", e);
        throw new InvalidParameterValueException("Please provide valid guest vlan range");
    }
    // Verify guest vlan range exists in the system
    List<Pair<Integer, Integer>> existingRanges = physicalNetwork.getVnet();
    Boolean exists = false;
    if (!existingRanges.isEmpty()) {
        for (int i = 0; i < existingRanges.size(); i++) {
            int existingStartVlan = existingRanges.get(i).first();
            int existingEndVlan = existingRanges.get(i).second();
            if (startVlan <= endVlan && startVlan >= existingStartVlan && endVlan <= existingEndVlan) {
                exists = true;
                break;
            }
        }
        if (!exists) {
            throw new InvalidParameterValueException("Unable to find guest vlan by range " + vlan);
        }
    }
    // Verify guest vlans in the range don't belong to a network of a different account
    for (int i = startVlan; i <= endVlan; i++) {
        List<DataCenterVnetVO> allocatedVlans = _datacneterVnet.listAllocatedVnetsInRange(physicalNetwork.getDataCenterId(), physicalNetwork.getId(), startVlan, endVlan);
        if (allocatedVlans != null && !allocatedVlans.isEmpty()) {
            for (DataCenterVnetVO allocatedVlan : allocatedVlans) {
                if (allocatedVlan.getAccountId() != vlanOwner.getAccountId()) {
                    throw new InvalidParameterValueException("Guest vlan from this range " + allocatedVlan.getVnet() + " is allocated to a different account." + " Can only dedicate a range which has no allocated vlans or has vlans allocated to the same account ");
                }
            }
        }
    }
    List<AccountGuestVlanMapVO> guestVlanMaps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByPhysicalNetwork(physicalNetworkId);
    // Verify if vlan range is already dedicated
    for (AccountGuestVlanMapVO guestVlanMap : guestVlanMaps) {
        List<Integer> vlanTokens = getVlanFromRange(guestVlanMap.getGuestVlanRange());
        int dedicatedStartVlan = vlanTokens.get(0).intValue();
        int dedicatedEndVlan = vlanTokens.get(1).intValue();
        if ((startVlan < dedicatedStartVlan & endVlan >= dedicatedStartVlan) || (startVlan >= dedicatedStartVlan & startVlan <= dedicatedEndVlan)) {
            throw new InvalidParameterValueException("Vlan range is already dedicated. Cannot" + " dedicate guest vlan range " + vlan);
        }
    }
    // Sort the existing dedicated vlan ranges
    Collections.sort(guestVlanMaps, new Comparator<AccountGuestVlanMapVO>() {

        @Override
        public int compare(AccountGuestVlanMapVO obj1, AccountGuestVlanMapVO obj2) {
            List<Integer> vlanTokens1 = getVlanFromRange(obj1.getGuestVlanRange());
            List<Integer> vlanTokens2 = getVlanFromRange(obj2.getGuestVlanRange());
            return vlanTokens1.get(0).compareTo(vlanTokens2.get(0));
        }
    });
    // Verify if vlan range extends an already dedicated range
    for (int i = 0; i < guestVlanMaps.size(); i++) {
        guestVlanMapId = guestVlanMaps.get(i).getId();
        guestVlanMapAccountId = guestVlanMaps.get(i).getAccountId();
        List<Integer> vlanTokens1 = getVlanFromRange(guestVlanMaps.get(i).getGuestVlanRange());
        // Range extends a dedicated vlan range to the left
        if (endVlan == (vlanTokens1.get(0).intValue() - 1)) {
            if (guestVlanMapAccountId == vlanOwnerId) {
                updatedVlanRange = startVlan + "-" + vlanTokens1.get(1).intValue();
            }
            break;
        }
        // Range extends a dedicated vlan range to the right
        if (startVlan == (vlanTokens1.get(1).intValue() + 1) & guestVlanMapAccountId == vlanOwnerId) {
            if (i != (guestVlanMaps.size() - 1)) {
                List<Integer> vlanTokens2 = getVlanFromRange(guestVlanMaps.get(i + 1).getGuestVlanRange());
                // Range extends 2 vlan ranges, both to the right and left
                if (endVlan == (vlanTokens2.get(0).intValue() - 1) && guestVlanMaps.get(i + 1).getAccountId() == vlanOwnerId) {
                    _datacneterVnet.releaseDedicatedGuestVlans(guestVlanMaps.get(i + 1).getId());
                    _accountGuestVlanMapDao.remove(guestVlanMaps.get(i + 1).getId());
                    updatedVlanRange = vlanTokens1.get(0).intValue() + "-" + vlanTokens2.get(1).intValue();
                    break;
                }
            }
            updatedVlanRange = vlanTokens1.get(0).intValue() + "-" + endVlan;
            break;
        }
    }
    // Dedicate vlan range
    AccountGuestVlanMapVO accountGuestVlanMapVO;
    if (updatedVlanRange != null) {
        accountGuestVlanMapVO = _accountGuestVlanMapDao.findById(guestVlanMapId);
        accountGuestVlanMapVO.setGuestVlanRange(updatedVlanRange);
        _accountGuestVlanMapDao.update(guestVlanMapId, accountGuestVlanMapVO);
    } else {
        accountGuestVlanMapVO = new AccountGuestVlanMapVO(vlanOwner.getAccountId(), physicalNetworkId);
        accountGuestVlanMapVO.setGuestVlanRange(startVlan + "-" + endVlan);
        _accountGuestVlanMapDao.persist(accountGuestVlanMapVO);
    }
    // For every guest vlan set the corresponding account guest vlan map id
    List<Integer> finaVlanTokens = getVlanFromRange(accountGuestVlanMapVO.getGuestVlanRange());
    for (int i = finaVlanTokens.get(0).intValue(); i <= finaVlanTokens.get(1).intValue(); i++) {
        List<DataCenterVnetVO> dataCenterVnet = _datacneterVnet.findVnet(physicalNetwork.getDataCenterId(), physicalNetworkId, Integer.toString(i));
        dataCenterVnet.get(0).setAccountGuestVlanMapId(accountGuestVlanMapVO.getId());
        _datacneterVnet.update(dataCenterVnet.get(0).getId(), dataCenterVnet.get(0));
    }
    return accountGuestVlanMapVO;
}
Also used : Account(com.cloud.user.Account) AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) Project(com.cloud.projects.Project) DataCenterVnetVO(com.cloud.dc.DataCenterVnetVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

ActionEvent (com.cloud.event.ActionEvent)209 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)174 Account (com.cloud.user.Account)114 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)80 DB (com.cloud.utils.db.DB)79 TransactionStatus (com.cloud.utils.db.TransactionStatus)40 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)32 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)32 ArrayList (java.util.ArrayList)31 CallContext (org.apache.cloudstack.context.CallContext)22 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)20 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)20 DataCenterVO (com.cloud.dc.DataCenterVO)18 Network (com.cloud.network.Network)18 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)17 InvalidParameterException (java.security.InvalidParameterException)16 List (java.util.List)16 NetworkVO (com.cloud.network.dao.NetworkVO)15 ConfigurationException (javax.naming.ConfigurationException)15 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)14