Search in sources :

Example 31 with TransactionCallbackNoReturn

use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.

the class RemoteAccessVpnManagerImpl method destroyRemoteAccessVpnForIp.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY, eventDescription = "removing remote access vpn", async = true)
public boolean destroyRemoteAccessVpnForIp(final long ipId, final Account caller) throws ResourceUnavailableException {
    final RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findByPublicIpAddress(ipId);
    if (vpn == null) {
        s_logger.debug("there are no Remote access vpns for public ip address id=" + ipId);
        return true;
    }
    _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, vpn);
    final RemoteAccessVpn.State prevState = vpn.getState();
    vpn.setState(RemoteAccessVpn.State.Removed);
    _remoteAccessVpnDao.update(vpn.getId(), vpn);
    boolean success = false;
    try {
        for (final RemoteAccessVPNServiceProvider element : _vpnServiceProviders) {
            if (element.stopVpn(vpn)) {
                success = true;
                break;
            }
        }
    } catch (final ResourceUnavailableException ex) {
        vpn.setState(prevState);
        _remoteAccessVpnDao.update(vpn.getId(), vpn);
        s_logger.debug("Failed to stop the vpn " + vpn.getId() + " , so reverted state to " + RemoteAccessVpn.State.Running);
        success = false;
    } finally {
        if (success) {
            // Cleanup corresponding ports
            final List<? extends FirewallRule> vpnFwRules = _rulesDao.listByIpAndPurpose(ipId, Purpose.Vpn);
            boolean applyFirewall = false;
            final List<FirewallRuleVO> fwRules = new ArrayList<>();
            // if related firewall rule is created for the first vpn port, it would be created for the 2 other ports as well, so need to cleanup the backend
            if (vpnFwRules.size() != 0 && _rulesDao.findByRelatedId(vpnFwRules.get(0).getId()) != null) {
                applyFirewall = true;
            }
            if (applyFirewall) {
                Transaction.execute(new TransactionCallbackNoReturn() {

                    @Override
                    public void doInTransactionWithoutResult(final TransactionStatus status) {
                        for (final FirewallRule vpnFwRule : vpnFwRules) {
                            // don't apply on the backend yet; send all 3 rules in a banch
                            _firewallMgr.revokeRelatedFirewallRule(vpnFwRule.getId(), false);
                            fwRules.add(_rulesDao.findByRelatedId(vpnFwRule.getId()));
                        }
                        s_logger.debug("Marked " + fwRules.size() + " firewall rules as Revoked as a part of disable remote access vpn");
                    }
                });
                // now apply vpn rules on the backend
                s_logger.debug("Reapplying firewall rules for ip id=" + ipId + " as a part of disable remote access vpn");
                success = _firewallMgr.applyIngressFirewallRules(ipId, caller);
            }
            if (success) {
                try {
                    Transaction.execute(new TransactionCallbackNoReturn() {

                        @Override
                        public void doInTransactionWithoutResult(final TransactionStatus status) {
                            _remoteAccessVpnDao.remove(vpn.getId());
                            // Stop billing of VPN users when VPN is removed. VPN_User_ADD events will be generated when VPN is created again
                            if (vpnFwRules != null) {
                                for (final FirewallRule vpnFwRule : vpnFwRules) {
                                    _rulesDao.remove(vpnFwRule.getId());
                                    s_logger.debug("Successfully removed firewall rule with ip id=" + vpnFwRule.getSourceIpAddressId() + " and port " + vpnFwRule.getSourcePortStart().intValue() + " as a part of vpn cleanup");
                                }
                            }
                        }
                    });
                } catch (final Exception ex) {
                    s_logger.warn("Unable to release the three vpn ports from the firewall rules", ex);
                }
            }
        }
    }
    return success;
}
Also used : RemoteAccessVPNServiceProvider(com.cloud.network.element.RemoteAccessVPNServiceProvider) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) AccountLimitException(com.cloud.exception.AccountLimitException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) FirewallRule(com.cloud.network.rules.FirewallRule) RemoteAccessVpn(com.cloud.network.RemoteAccessVpn) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 32 with TransactionCallbackNoReturn

use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.

the class RemoteAccessVpnManagerImpl method applyVpnUsers.

@DB
@Override
public boolean applyVpnUsers(final long vpnOwnerId, final String userName) {
    final Account caller = CallContext.current().getCallingAccount();
    final Account owner = _accountDao.findById(vpnOwnerId);
    _accountMgr.checkAccess(caller, null, true, owner);
    s_logger.debug("Applying vpn users for " + owner);
    final List<RemoteAccessVpnVO> vpns = _remoteAccessVpnDao.findByAccount(vpnOwnerId);
    if (vpns.size() == 0) {
        throw new InvalidParameterValueException("No Remote Access VPN configuration can be found for account " + owner.getAccountName());
    }
    final List<VpnUserVO> users = _vpnUsersDao.listByAccount(vpnOwnerId);
    // If user is in Active state, we still have to resend them therefore their status has to be Add
    for (final VpnUserVO user : users) {
        if (user.getState() == State.Active) {
            user.setState(State.Add);
            _vpnUsersDao.update(user.getId(), user);
        }
    }
    boolean success = true;
    final Boolean[] finals = new Boolean[users.size()];
    for (final RemoteAccessVPNServiceProvider element : _vpnServiceProviders) {
        s_logger.debug("Applying vpn access to " + element.getName());
        for (final RemoteAccessVpnVO vpn : vpns) {
            try {
                final String[] results = element.applyVpnUsers(vpn, users);
                if (results != null) {
                    int indexUser = -1;
                    for (int i = 0; i < results.length; i++) {
                        indexUser++;
                        if (indexUser == users.size()) {
                            // results on multiple VPC routers are combined in commit 13eb789, reset user index if one VR is done.
                            indexUser = 0;
                        }
                        s_logger.debug("VPN User " + users.get(indexUser) + (results[i] == null ? " is set on " : (" couldn't be set due to " + results[i]) + " on ") + vpn.getUuid());
                        if (results[i] == null) {
                            if (finals[indexUser] == null) {
                                finals[indexUser] = true;
                            }
                        } else {
                            finals[indexUser] = false;
                            success = false;
                        }
                    }
                }
            } catch (final Exception e) {
                s_logger.warn("Unable to apply vpn users ", e);
                success = false;
                for (int i = 0; i < finals.length; i++) {
                    finals[i] = false;
                }
            }
        }
    }
    for (int i = 0; i < finals.length; i++) {
        final VpnUserVO user = users.get(i);
        if (finals[i]) {
            if (user.getState() == State.Add) {
                user.setState(State.Active);
                _vpnUsersDao.update(user.getId(), user);
            } else if (user.getState() == State.Revoke) {
                _vpnUsersDao.remove(user.getId());
            }
        } else {
            if (user.getState() == State.Add && (user.getUsername()).equals(userName)) {
                Transaction.execute(new TransactionCallbackNoReturn() {

                    @Override
                    public void doInTransactionWithoutResult(final TransactionStatus status) {
                        _vpnUsersDao.remove(user.getId());
                    }
                });
            }
            s_logger.warn("Failed to apply vpn for user " + user.getUsername() + ", accountId=" + user.getAccountId());
        }
    }
    return success;
}
Also used : Account(com.cloud.user.Account) RemoteAccessVPNServiceProvider(com.cloud.network.element.RemoteAccessVPNServiceProvider) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) VpnUserVO(com.cloud.network.VpnUserVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) AccountLimitException(com.cloud.exception.AccountLimitException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ConfigurationException(javax.naming.ConfigurationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) DB(com.cloud.utils.db.DB)

Example 33 with TransactionCallbackNoReturn

use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.

the class ProjectManagerImpl method activateProject.

@Override
@ActionEvent(eventType = EventTypes.EVENT_PROJECT_ACTIVATE, eventDescription = "activating project")
@DB
public Project activateProject(final long projectId) {
    final Account caller = CallContext.current().getCallingAccount();
    // check that the project exists
    final ProjectVO project = getProject(projectId);
    if (project == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id");
        ex.addProxyObject(String.valueOf(projectId), "projectId");
        throw ex;
    }
    // verify permissions
    _accountMgr.checkAccess(caller, AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId()));
    // allow project activation only when it's in Suspended state
    final Project.State currentState = project.getState();
    if (currentState == State.Active) {
        s_logger.debug("The project id=" + projectId + " is already active, no need to activate it again");
        return project;
    }
    if (currentState != State.Suspended) {
        throw new InvalidParameterValueException("Can't activate the project in " + currentState + " state");
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            project.setState(Project.State.Active);
            _projectDao.update(projectId, project);
            _accountMgr.enableAccount(project.getProjectAccountId());
        }
    });
    return _projectDao.findById(projectId);
}
Also used : Account(com.cloud.user.Account) State(com.cloud.projects.Project.State) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 34 with TransactionCallbackNoReturn

use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.

the class RulesManagerImpl method reservePorts.

@Override
@DB
public FirewallRuleVO[] reservePorts(final IpAddress ip, final String protocol, final FirewallRule.Purpose purpose, final boolean openFirewall, final Account caller, final int... ports) throws NetworkRuleConflictException {
    final FirewallRuleVO[] rules = new FirewallRuleVO[ports.length];
    Transaction.execute(new TransactionCallbackWithExceptionNoReturn<NetworkRuleConflictException>() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) throws NetworkRuleConflictException {
            for (int i = 0; i < ports.length; i++) {
                rules[i] = new FirewallRuleVO(null, ip.getId(), ports[i], protocol, ip.getAssociatedWithNetworkId(), ip.getAllocatedToAccountId(), ip.getAllocatedInDomainId(), purpose, null, null, null, null);
                rules[i] = _firewallDao.persist(rules[i]);
                if (openFirewall) {
                    _firewallMgr.createRuleForAllCidrs(ip.getId(), caller, ports[i], ports[i], protocol, null, null, rules[i].getId(), ip.getAssociatedWithNetworkId());
                }
            }
        }
    });
    boolean success = false;
    try {
        for (final FirewallRuleVO newRule : rules) {
            _firewallMgr.detectRulesConflict(newRule);
        }
        success = true;
        return rules;
    } finally {
        if (!success) {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    for (final FirewallRuleVO newRule : rules) {
                        _firewallMgr.removeRule(newRule);
                    }
                }
            });
        }
    }
}
Also used : TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) DB(com.cloud.utils.db.DB)

Example 35 with TransactionCallbackNoReturn

use of com.cloud.utils.db.TransactionCallbackNoReturn in project cosmic by MissionCriticalCloud.

the class StorageManagerImpl method deleteImageStore.

@Override
public boolean deleteImageStore(final DeleteImageStoreCmd cmd) {
    final long storeId = cmd.getId();
    // Verify that image store exists
    final ImageStoreVO store = _imageStoreDao.findById(storeId);
    if (store == null) {
        throw new InvalidParameterValueException("Image store with id " + storeId + " doesn't exist");
    }
    _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), store.getDataCenterId());
    // Verify that there are no live snapshot, template, volume on the image
    // store to be deleted
    final List<SnapshotDataStoreVO> snapshots = _snapshotStoreDao.listByStoreId(storeId, DataStoreRole.Image);
    if (snapshots != null && snapshots.size() > 0) {
        throw new InvalidParameterValueException("Cannot delete image store with active snapshots backup!");
    }
    final List<VolumeDataStoreVO> volumes = _volumeStoreDao.listByStoreId(storeId);
    if (volumes != null && volumes.size() > 0) {
        throw new InvalidParameterValueException("Cannot delete image store with active volumes backup!");
    }
    // search if there are user templates stored on this image store, excluding system, builtin templates
    final List<TemplateJoinVO> templates = _templateViewDao.listActiveTemplates(storeId);
    if (templates != null && templates.size() > 0) {
        throw new InvalidParameterValueException("Cannot delete image store with active templates backup!");
    }
    // ready to delete
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            // first delete from image_store_details table, we need to do that since
            // we are not actually deleting record from main
            // image_data_store table, so delete cascade will not work
            _imageStoreDetailsDao.deleteDetails(storeId);
            _snapshotStoreDao.deletePrimaryRecordsForStore(storeId, DataStoreRole.Image);
            _volumeStoreDao.deletePrimaryRecordsForStore(storeId);
            _templateStoreDao.deletePrimaryRecordsForStore(storeId);
            _imageStoreDao.remove(storeId);
        }
    });
    return true;
}
Also used : InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) SnapshotDataStoreVO(com.cloud.storage.datastore.db.SnapshotDataStoreVO) VolumeDataStoreVO(com.cloud.storage.datastore.db.VolumeDataStoreVO) TemplateJoinVO(com.cloud.api.query.vo.TemplateJoinVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ImageStoreVO(com.cloud.storage.datastore.db.ImageStoreVO)

Aggregations

TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)172 TransactionStatus (com.cloud.utils.db.TransactionStatus)172 DB (com.cloud.utils.db.DB)133 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)71 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)60 ArrayList (java.util.ArrayList)57 ActionEvent (com.cloud.event.ActionEvent)42 List (java.util.List)42 Account (com.cloud.user.Account)39 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)38 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)36 ConfigurationException (javax.naming.ConfigurationException)32 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)26 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)24 IPAddressVO (com.cloud.network.dao.IPAddressVO)24 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)23 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)18 HostVO (com.cloud.host.HostVO)18 HashMap (java.util.HashMap)18 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)17