Search in sources :

Example 41 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class RemoteAccessVpnManagerImpl method removeVpnUser.

@DB
@Override
public boolean removeVpnUser(long vpnOwnerId, String username, Account caller) {
    final VpnUserVO user = _vpnUsersDao.findByAccountAndUsername(vpnOwnerId, username);
    if (user == null) {
        String errorMessage = String.format("Could not find VPN user=[%s]. VPN owner id=[%s]", username, vpnOwnerId);
        s_logger.debug(errorMessage);
        throw new InvalidParameterValueException(errorMessage);
    }
    _accountMgr.checkAccess(caller, null, true, user);
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            user.setState(State.Revoke);
            _vpnUsersDao.update(user.getId(), user);
            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername(), user.getClass().getName(), user.getUuid());
        }
    });
    return true;
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) VpnUserVO(com.cloud.network.VpnUserVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) DB(com.cloud.utils.db.DB)

Example 42 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class RemoteAccessVpnManagerImpl method startRemoteAccessVpn.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE, eventDescription = "creating remote access vpn", async = true)
public RemoteAccessVpnVO startRemoteAccessVpn(long ipAddressId, boolean openFirewall) throws ResourceUnavailableException {
    Account caller = CallContext.current().getCallingAccount();
    final RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findByPublicIpAddress(ipAddressId);
    if (vpn == null) {
        throw new InvalidParameterValueException("Unable to find your vpn: " + ipAddressId);
    }
    if (vpn.getVpcId() != null) {
        openFirewall = false;
    }
    _accountMgr.checkAccess(caller, null, true, vpn);
    boolean started = false;
    try {
        boolean firewallOpened = true;
        if (openFirewall) {
            firewallOpened = _firewallMgr.applyIngressFirewallRules(vpn.getServerAddressId(), caller);
        }
        if (firewallOpened) {
            for (RemoteAccessVPNServiceProvider element : _vpnServiceProviders) {
                if (element.startVpn(vpn)) {
                    started = true;
                    break;
                }
            }
        }
        return vpn;
    } finally {
        if (started) {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    vpn.setState(RemoteAccessVpn.State.Running);
                    _remoteAccessVpnDao.update(vpn.getId(), vpn);
                    List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
                    for (VpnUserVO user : vpnUsers) {
                        if (user.getState() != VpnUser.State.Revoke) {
                            UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername(), user.getClass().getName(), user.getUuid());
                        }
                    }
                }
            });
        }
    }
}
Also used : Account(com.cloud.user.Account) RemoteAccessVPNServiceProvider(com.cloud.network.element.RemoteAccessVPNServiceProvider) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) VpnUserVO(com.cloud.network.VpnUserVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) List(java.util.List) ArrayList(java.util.ArrayList) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 43 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class RulesManagerImpl method createStaticNatRule.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "creating static nat rule", create = true)
public StaticNatRule createStaticNatRule(final StaticNatRule rule, final boolean openFirewall) throws NetworkRuleConflictException {
    final Account caller = CallContext.current().getCallingAccount();
    final Long ipAddrId = rule.getSourceIpAddressId();
    IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
    // Validate ip address
    if (ipAddress == null) {
        throw new InvalidParameterValueException("Unable to create static nat rule; ip id=" + ipAddrId + " doesn't exist in the system");
    } else if (ipAddress.isSourceNat() || !ipAddress.isOneToOneNat() || ipAddress.getAssociatedWithVmId() == null) {
        throw new NetworkRuleConflictException("Can't do static nat on ip address: " + ipAddress.getAddress());
    }
    _firewallMgr.validateFirewallRule(caller, ipAddress, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), Purpose.StaticNat, FirewallRuleType.User, null, rule.getTrafficType());
    final Long networkId = ipAddress.getAssociatedWithNetworkId();
    final Long accountId = ipAddress.getAllocatedToAccountId();
    final Long domainId = ipAddress.getAllocatedInDomainId();
    _networkModel.checkIpForService(ipAddress, Service.StaticNat, null);
    Network network = _networkModel.getNetwork(networkId);
    NetworkOffering off = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
    if (off.isElasticIp()) {
        throw new InvalidParameterValueException("Can't create ip forwarding rules for the network where elasticIP service is enabled");
    }
    // String dstIp = _networkModel.getIpInNetwork(ipAddress.getAssociatedWithVmId(), networkId);
    final String dstIp = ipAddress.getVmIp();
    return Transaction.execute(new TransactionCallbackWithException<StaticNatRule, NetworkRuleConflictException>() {

        @Override
        public StaticNatRule doInTransaction(TransactionStatus status) throws NetworkRuleConflictException {
            FirewallRuleVO newRule = new FirewallRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol().toLowerCase(), networkId, accountId, domainId, rule.getPurpose(), null, null, null, null, null);
            newRule = _firewallDao.persist(newRule);
            // create firewallRule for 0.0.0.0/0 cidr
            if (openFirewall) {
                _firewallMgr.createRuleForAllCidrs(ipAddrId, caller, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), null, null, newRule.getId(), networkId);
            }
            try {
                _firewallMgr.detectRulesConflict(newRule);
                if (!_firewallDao.setStateToAdd(newRule)) {
                    throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
                }
                CallContext.current().setEventDetails("Rule Id: " + newRule.getId());
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_NET_RULE_ADD, newRule.getAccountId(), 0, newRule.getId(), null, FirewallRule.class.getName(), newRule.getUuid());
                StaticNatRule staticNatRule = new StaticNatRuleImpl(newRule, dstIp);
                return staticNatRule;
            } catch (Exception e) {
                if (newRule != null) {
                    // no need to apply the rule as it wasn't programmed on the backend yet
                    _firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
                    _firewallMgr.removeRule(newRule);
                }
                if (e instanceof NetworkRuleConflictException) {
                    throw (NetworkRuleConflictException) e;
                }
                throw new CloudRuntimeException("Unable to add static nat rule for the ip id=" + newRule.getSourceIpAddressId(), e);
            }
        }
    });
}
Also used : Account(com.cloud.user.Account) NetworkOffering(com.cloud.offering.NetworkOffering) TransactionStatus(com.cloud.utils.db.TransactionStatus) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) 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) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) IPAddressVO(com.cloud.network.dao.IPAddressVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 44 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class SecurityGroupManagerImpl method revokeSecurityGroupRule.

private boolean revokeSecurityGroupRule(final Long id, SecurityRuleType type) {
    // input validation
    Account caller = CallContext.current().getCallingAccount();
    final SecurityGroupRuleVO rule = _securityGroupRuleDao.findById(id);
    if (rule == null) {
        s_logger.debug("Unable to find security rule with id " + id);
        throw new InvalidParameterValueException("Unable to find security rule with id " + id);
    }
    // check type
    if (type != rule.getRuleType()) {
        s_logger.debug("Mismatch in rule type for security rule with id " + id);
        throw new InvalidParameterValueException("Mismatch in rule type for security rule with id " + id);
    }
    // Check permissions
    SecurityGroup securityGroup = _securityGroupDao.findById(rule.getSecurityGroupId());
    _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, securityGroup);
    long securityGroupId = rule.getSecurityGroupId();
    Boolean result = Transaction.execute(new TransactionCallback<Boolean>() {

        @Override
        public Boolean doInTransaction(TransactionStatus status) {
            SecurityGroupVO groupHandle = null;
            try {
                // acquire lock on parent group (preserving this logic)
                groupHandle = _securityGroupDao.acquireInLockTable(rule.getSecurityGroupId());
                if (groupHandle == null) {
                    s_logger.warn("Could not acquire lock on security group id: " + rule.getSecurityGroupId());
                    return false;
                }
                _securityGroupRuleDao.remove(id);
                s_logger.debug("revokeSecurityGroupRule succeeded for security rule id: " + id);
                return true;
            } catch (Exception e) {
                s_logger.warn("Exception caught when deleting security rules ", e);
                throw new CloudRuntimeException("Exception caught when deleting security rules", e);
            } finally {
                if (groupHandle != null) {
                    _securityGroupDao.releaseFromLockTable(groupHandle.getId());
                }
            }
        }
    });
    try {
        final ArrayList<Long> affectedVms = new ArrayList<Long>();
        affectedVms.addAll(_securityGroupVMMapDao.listVmIdsBySecurityGroup(securityGroupId));
        scheduleRulesetUpdateToHosts(affectedVms, true, null);
    } catch (Exception e) {
        s_logger.debug("Can't update rules for host, ignore", e);
    }
    return result;
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) ConcurrentModificationException(java.util.ConcurrentModificationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceInUseException(com.cloud.exception.ResourceInUseException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Example 45 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class SecurityGroupManagerImpl method updateSecurityGroup.

@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_SECURITY_GROUP_UPDATE, eventDescription = "updating security group")
public SecurityGroup updateSecurityGroup(UpdateSecurityGroupCmd cmd) {
    final Long groupId = cmd.getId();
    final String newName = cmd.getName();
    Account caller = CallContext.current().getCallingAccount();
    SecurityGroupVO group = _securityGroupDao.findById(groupId);
    if (group == null) {
        throw new InvalidParameterValueException("Unable to find security group: " + groupId + "; failed to update security group.");
    }
    if (newName == null) {
        s_logger.debug("security group name is not changed. id=" + groupId);
        return group;
    }
    if (StringUtils.isBlank(newName)) {
        throw new InvalidParameterValueException("Security group name cannot be empty");
    }
    // check permissions
    _accountMgr.checkAccess(caller, null, true, group);
    return Transaction.execute(new TransactionCallback<SecurityGroupVO>() {

        @Override
        public SecurityGroupVO doInTransaction(TransactionStatus status) {
            SecurityGroupVO group = _securityGroupDao.lockRow(groupId, true);
            if (group == null) {
                throw new InvalidParameterValueException("Unable to find security group by id " + groupId);
            }
            if (newName.equals(group.getName())) {
                s_logger.debug("security group name is not changed. id=" + groupId);
                return group;
            } else if (newName.equalsIgnoreCase(SecurityGroupManager.DEFAULT_GROUP_NAME)) {
                throw new InvalidParameterValueException("The security group name " + SecurityGroupManager.DEFAULT_GROUP_NAME + " is reserved");
            }
            if (group.getName().equalsIgnoreCase(SecurityGroupManager.DEFAULT_GROUP_NAME)) {
                throw new InvalidParameterValueException("The default security group cannot be renamed");
            }
            group.setName(newName);
            _securityGroupDao.update(groupId, group);
            s_logger.debug("Updated security group id=" + groupId);
            return group;
        }
    });
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionStatus(com.cloud.utils.db.TransactionStatus) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

TransactionStatus (com.cloud.utils.db.TransactionStatus)323 DB (com.cloud.utils.db.DB)257 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)172 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)150 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)117 ArrayList (java.util.ArrayList)104 Account (com.cloud.user.Account)93 List (java.util.List)89 ActionEvent (com.cloud.event.ActionEvent)88 ConfigurationException (javax.naming.ConfigurationException)71 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)64 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)64 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)50 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)49 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)47 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)45 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)45 IPAddressVO (com.cloud.network.dao.IPAddressVO)43 HashMap (java.util.HashMap)38 Network (com.cloud.network.Network)37