Search in sources :

Example 41 with Account

use of com.cloud.legacymodel.user.Account in project cosmic by MissionCriticalCloud.

the class RemoteAccessVpnManagerImpl method searchForVpnUsers.

@Override
public Pair<List<? extends VpnUser>, Integer> searchForVpnUsers(final ListVpnUsersCmd cmd) {
    final String username = cmd.getUsername();
    final Long id = cmd.getId();
    final Account caller = CallContext.current().getCallingAccount();
    final List<Long> permittedAccounts = new ArrayList<>();
    final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
    final Long domainId = domainIdRecursiveListProject.first();
    final Boolean isRecursive = domainIdRecursiveListProject.second();
    final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    final Filter searchFilter = new Filter(VpnUserVO.class, "username", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    final SearchBuilder<VpnUserVO> sb = _vpnUsersDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.EQ);
    sb.and("state", sb.entity().getState(), Op.IN);
    final SearchCriteria<VpnUserVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    // list only active users
    sc.setParameters("state", State.Active, State.Add);
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (username != null) {
        sc.setParameters("username", username);
    }
    final Pair<List<VpnUserVO>, Integer> result = _vpnUsersDao.searchAndCount(sc, searchFilter);
    return new Pair<>(result.first(), result.second());
}
Also used : Account(com.cloud.legacymodel.user.Account) Ternary(com.cloud.legacymodel.utils.Ternary) VpnUserVO(com.cloud.network.VpnUserVO) ArrayList(java.util.ArrayList) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) Filter(com.cloud.utils.db.Filter) List(java.util.List) ArrayList(java.util.ArrayList) Pair(com.cloud.legacymodel.utils.Pair)

Example 42 with Account

use of com.cloud.legacymodel.user.Account in project cosmic by MissionCriticalCloud.

the class RemoteAccessVpnManagerImpl method listVpnUsers.

@Override
public List<? extends VpnUser> listVpnUsers(final long vpnOwnerId, final String userName) {
    final Account caller = CallContext.current().getCallingAccount();
    final Account owner = _accountDao.findById(vpnOwnerId);
    _accountMgr.checkAccess(caller, null, true, owner);
    return _vpnUsersDao.listByAccount(vpnOwnerId);
}
Also used : Account(com.cloud.legacymodel.user.Account)

Example 43 with Account

use of com.cloud.legacymodel.user.Account in project cosmic by MissionCriticalCloud.

the class RemoteAccessVpnManagerImpl method createRemoteAccessVpn.

@Override
@DB
public RemoteAccessVpn createRemoteAccessVpn(final long publicIpId, String ipRange, boolean openFirewall, final Boolean forDisplay) throws NetworkRuleConflictException {
    final CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    final Long networkId;
    // make sure ip address exists
    final PublicIpAddress ipAddr = _networkMgr.getPublicIpAddress(publicIpId);
    if (ipAddr == null) {
        throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address id" + publicIpId);
    }
    _accountMgr.checkAccess(caller, null, true, ipAddr);
    if (!ipAddr.readyToUse()) {
        throw new InvalidParameterValueException("The Ip address is not ready to be used yet: " + ipAddr.getAddress());
    }
    final IPAddressVO ipAddress = _ipAddressDao.findById(publicIpId);
    networkId = ipAddress.getAssociatedWithNetworkId();
    if (networkId != null) {
        _networkMgr.checkIpForService(ipAddress, Service.Vpn, null);
    }
    final Long vpcId = ipAddress.getVpcId();
    /* IP Address used for VPC must be the source NAT IP of whole VPC */
    if (vpcId != null && ipAddress.isSourceNat()) {
        assert networkId == null;
        // No firewall setting for VPC, it would be open internally
        openFirewall = false;
    }
    final boolean openFirewallFinal = openFirewall;
    if (networkId == null && vpcId == null) {
        throw new InvalidParameterValueException("Unable to create remote access vpn for the ipAddress: " + ipAddr.getAddress().addr() + " as ip is not associated with any network or VPC");
    }
    RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIpId);
    if (vpnVO != null) {
        // if vpn is in Added state, return it to the api
        if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
            return vpnVO;
        }
        throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address");
    }
    if (ipRange == null) {
        ipRange = RemoteAccessVpnClientIpRange.valueIn(ipAddr.getAccountId());
    }
    final String[] range = ipRange.split("-");
    if (range.length != 2) {
        throw new InvalidParameterValueException("Invalid ip range");
    }
    if (!NetUtils.isValidIp4(range[0]) || !NetUtils.isValidIp4(range[1])) {
        throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange);
    }
    if (!NetUtils.validIpRange(range[0], range[1])) {
        throw new InvalidParameterValueException("Invalid ip range " + ipRange);
    }
    final Pair<String, Integer> cidr;
    // TODO: assumes one virtual network / domr per account per zone
    if (networkId != null) {
        vpnVO = _remoteAccessVpnDao.findByAccountAndNetwork(ipAddr.getAccountId(), networkId);
        if (vpnVO != null) {
            // if vpn is in Added state, return it to the api
            if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
                return vpnVO;
            }
            throw new InvalidParameterValueException("A Remote Access VPN already exists for this account");
        }
        // Verify that vpn service is enabled for the network
        final Network network = _networkMgr.getNetwork(networkId);
        if (!_networkMgr.areServicesSupportedInNetwork(network.getId(), Service.Vpn)) {
            throw new InvalidParameterValueException("Vpn service is not supported in network id=" + ipAddr.getAssociatedWithNetworkId());
        }
        cidr = NetUtils.getCidr(network.getCidr());
    } else {
        // Don't need to check VPC because there is only one IP(source NAT IP) available for VPN
        final Vpc vpc = _vpcDao.findById(vpcId);
        cidr = NetUtils.getCidr(vpc.getCidr());
    }
    // FIXME: This check won't work for the case where the guest ip range
    // changes depending on the vlan allocated.
    final String[] guestIpRange = NetUtils.getIpRangeFromCidr(cidr.first(), cidr.second());
    if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) {
        throw new InvalidParameterValueException("Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-" + guestIpRange[1]);
    }
    // TODO: check sufficient range
    // TODO: check overlap with private and public ip ranges in datacenter
    long startIp = NetUtils.ip2Long(range[0]);
    final String newIpRange = NetUtils.long2Ip(++startIp) + "-" + range[1];
    final String sharedSecret = PasswordGenerator.generatePresharedKey(_pskLength);
    return Transaction.execute(new TransactionCallbackWithException<RemoteAccessVpn, NetworkRuleConflictException>() {

        @Override
        public RemoteAccessVpn doInTransaction(final TransactionStatus status) throws NetworkRuleConflictException {
            if (vpcId == null) {
                _rulesMgr.reservePorts(ipAddr, NetUtils.UDP_PROTO, Purpose.Vpn, openFirewallFinal, caller, NetUtils.VPN_PORT, NetUtils.VPN_L2TP_PORT, NetUtils.VPN_NATT_PORT);
            }
            final RemoteAccessVpnVO vpnVO = new RemoteAccessVpnVO(ipAddr.getAccountId(), ipAddr.getDomainId(), ipAddr.getAssociatedWithNetworkId(), publicIpId, vpcId, range[0], newIpRange, sharedSecret);
            if (forDisplay != null) {
                vpnVO.setDisplay(forDisplay);
            }
            return _remoteAccessVpnDao.persist(vpnVO);
        }
    });
}
Also used : Account(com.cloud.legacymodel.user.Account) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) Vpc(com.cloud.legacymodel.network.vpc.Vpc) TransactionStatus(com.cloud.utils.db.TransactionStatus) CallContext(com.cloud.context.CallContext) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) PublicIpAddress(com.cloud.network.PublicIpAddress) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Network(com.cloud.legacymodel.network.Network) IPAddressVO(com.cloud.network.dao.IPAddressVO) RemoteAccessVpn(com.cloud.network.RemoteAccessVpn) DB(com.cloud.utils.db.DB)

Example 44 with Account

use of com.cloud.legacymodel.user.Account 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.legacymodel.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) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) AccountLimitException(com.cloud.legacymodel.exceptions.AccountLimitException) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) DB(com.cloud.utils.db.DB)

Example 45 with Account

use of com.cloud.legacymodel.user.Account in project cosmic by MissionCriticalCloud.

the class Site2SiteVpnManagerImpl method searchForVpnGateways.

@Override
public Pair<List<? extends Site2SiteVpnGateway>, Integer> searchForVpnGateways(final ListVpnGatewaysCmd cmd) {
    final Long id = cmd.getId();
    final Long vpcId = cmd.getVpcId();
    final Boolean display = cmd.getDisplay();
    Long domainId = cmd.getDomainId();
    boolean isRecursive = cmd.isRecursive();
    final String accountName = cmd.getAccountName();
    final boolean listAll = cmd.listAll();
    final long startIndex = cmd.getStartIndex();
    final long pageSizeVal = cmd.getPageSizeVal();
    final Account caller = CallContext.current().getCallingAccount();
    final List<Long> permittedAccounts = new ArrayList<>();
    final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(domainId, isRecursive, null);
    _accountMgr.buildACLSearchParameters(caller, id, accountName, cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false);
    domainId = domainIdRecursiveListProject.first();
    isRecursive = domainIdRecursiveListProject.second();
    final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    final Filter searchFilter = new Filter(Site2SiteVpnGatewayVO.class, "id", false, startIndex, pageSizeVal);
    final SearchBuilder<Site2SiteVpnGatewayVO> sb = _vpnGatewayDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ);
    sb.and("display", sb.entity().isDisplay(), SearchCriteria.Op.EQ);
    final SearchCriteria<Site2SiteVpnGatewayVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    if (id != null) {
        sc.addAnd("id", SearchCriteria.Op.EQ, id);
    }
    if (display != null) {
        sc.setParameters("display", display);
    }
    if (vpcId != null) {
        sc.addAnd("vpcId", SearchCriteria.Op.EQ, vpcId);
    }
    final Pair<List<Site2SiteVpnGatewayVO>, Integer> result = _vpnGatewayDao.searchAndCount(sc, searchFilter);
    return new Pair<>(result.first(), result.second());
}
Also used : Account(com.cloud.legacymodel.user.Account) Ternary(com.cloud.legacymodel.utils.Ternary) ArrayList(java.util.ArrayList) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) Filter(com.cloud.utils.db.Filter) Site2SiteVpnGatewayVO(com.cloud.network.dao.Site2SiteVpnGatewayVO) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) Pair(com.cloud.legacymodel.utils.Pair)

Aggregations

Account (com.cloud.legacymodel.user.Account)435 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)229 ActionEvent (com.cloud.event.ActionEvent)120 ArrayList (java.util.ArrayList)103 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)98 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)78 User (com.cloud.legacymodel.user.User)73 DB (com.cloud.utils.db.DB)59 List (java.util.List)58 Pair (com.cloud.legacymodel.utils.Pair)53 Network (com.cloud.legacymodel.network.Network)48 CallContext (com.cloud.context.CallContext)47 DomainVO (com.cloud.domain.DomainVO)47 UserAccount (com.cloud.legacymodel.user.UserAccount)47 Filter (com.cloud.utils.db.Filter)47 TransactionStatus (com.cloud.utils.db.TransactionStatus)40 Domain (com.cloud.legacymodel.domain.Domain)39 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)37 Test (org.junit.Test)36 Ternary (com.cloud.legacymodel.utils.Ternary)34