Search in sources :

Example 51 with InvalidParameterValueException

use of com.cloud.legacymodel.exceptions.InvalidParameterValueException in project cosmic by MissionCriticalCloud.

the class VpcManagerImpl method startVpc.

@Override
public boolean startVpc(final long vpcId, final boolean destroyOnFailure) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    final CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    final User callerUser = _accountMgr.getActiveUser(ctx.getCallingUserId());
    // check if vpc exists
    final Vpc vpc = getActiveVpc(vpcId);
    if (vpc == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC by id specified");
        ex.addProxyObject(String.valueOf(vpcId), "VPC");
        throw ex;
    }
    // permission check
    _accountMgr.checkAccess(caller, null, false, vpc);
    final Zone zone = zoneRepository.findById(vpc.getZoneId()).orElse(null);
    final DeployDestination dest = new DeployDestination(zone, null, null, null);
    final ReservationContext context = new ReservationContextImpl(null, null, callerUser, _accountMgr.getAccount(vpc.getAccountId()));
    boolean result = true;
    try {
        if (!startVpc(vpc, dest, context)) {
            s_logger.warn("Failed to start vpc " + vpc);
            result = false;
        }
    } catch (final Exception ex) {
        s_logger.warn("Failed to start vpc " + vpc + " due to ", ex);
        result = false;
    } finally {
        // do cleanup
        if (!result && destroyOnFailure) {
            s_logger.debug("Destroying vpc " + vpc + " that failed to start");
            if (destroyVpc(vpc, caller, callerUser.getId())) {
                s_logger.warn("Successfully destroyed vpc " + vpc + " that failed to start");
            } else {
                s_logger.warn("Failed to destroy vpc " + vpc + " that failed to start");
            }
        }
    }
    return result;
}
Also used : Account(com.cloud.legacymodel.user.Account) User(com.cloud.legacymodel.user.User) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Zone(com.cloud.db.model.Zone) DeployDestination(com.cloud.deploy.DeployDestination) Vpc(com.cloud.legacymodel.network.vpc.Vpc) CallContext(com.cloud.context.CallContext) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) ExecutionException(java.util.concurrent.ExecutionException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ServerApiException(com.cloud.api.ServerApiException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) ReservationContext(com.cloud.vm.ReservationContext)

Example 52 with InvalidParameterValueException

use of com.cloud.legacymodel.exceptions.InvalidParameterValueException in project cosmic by MissionCriticalCloud.

the class VpcManagerImpl method revokeStaticRoute.

@Override
@ActionEvent(eventType = EventTypes.EVENT_STATIC_ROUTE_DELETE, eventDescription = "deleting static route")
public boolean revokeStaticRoute(final long routeId) throws ResourceUnavailableException {
    final Account caller = CallContext.current().getCallingAccount();
    final StaticRouteVO route = _staticRouteDao.findById(routeId);
    if (route == null) {
        throw new InvalidParameterValueException("Unable to find static route by id");
    }
    _accountMgr.checkAccess(caller, null, false, route);
    markStaticRouteForRevoke(route, caller);
    return applyStaticRoutesForVpc(route.getVpcId());
}
Also used : Account(com.cloud.legacymodel.user.Account) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ActionEvent(com.cloud.event.ActionEvent)

Example 53 with InvalidParameterValueException

use of com.cloud.legacymodel.exceptions.InvalidParameterValueException 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 54 with InvalidParameterValueException

use of com.cloud.legacymodel.exceptions.InvalidParameterValueException 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 55 with InvalidParameterValueException

use of com.cloud.legacymodel.exceptions.InvalidParameterValueException in project cosmic by MissionCriticalCloud.

the class RemoteAccessVpnManagerImpl method updateRemoteAccessVpn.

@Override
@ActionEvent(eventType = EventTypes.EVENT_REMOTE_ACCESS_VPN_UPDATE, eventDescription = "updating remote access vpn", async = true)
public RemoteAccessVpn updateRemoteAccessVpn(final long id, final String customId, final Boolean forDisplay) {
    final RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findById(id);
    if (vpn == null) {
        throw new InvalidParameterValueException("Can't find remote access vpn by id " + id);
    }
    _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, vpn);
    if (customId != null) {
        vpn.setUuid(customId);
    }
    if (forDisplay != null) {
        vpn.setDisplay(forDisplay);
    }
    _remoteAccessVpnDao.update(vpn.getId(), vpn);
    return _remoteAccessVpnDao.findById(id);
}
Also used : RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ActionEvent(com.cloud.event.ActionEvent)

Aggregations

InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)483 Account (com.cloud.legacymodel.user.Account)219 ActionEvent (com.cloud.event.ActionEvent)159 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)153 ArrayList (java.util.ArrayList)105 DB (com.cloud.utils.db.DB)97 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)76 List (java.util.List)62 TransactionStatus (com.cloud.utils.db.TransactionStatus)58 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)53 Network (com.cloud.legacymodel.network.Network)51 ServerApiException (com.cloud.api.ServerApiException)47 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)43 Pair (com.cloud.legacymodel.utils.Pair)36 HashMap (java.util.HashMap)36 ConfigurationException (javax.naming.ConfigurationException)36 ResourceAllocationException (com.cloud.legacymodel.exceptions.ResourceAllocationException)33 NetworkVO (com.cloud.network.dao.NetworkVO)31 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)30 HostVO (com.cloud.host.HostVO)29