Search in sources :

Example 6 with PrivateGateway

use of com.cloud.legacymodel.network.vpc.PrivateGateway in project cosmic by MissionCriticalCloud.

the class CreatePrivateGatewayCmd method create.

// ///////////////////////////////////////////////////
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////
@Override
public void create() throws ResourceAllocationException {
    PrivateGateway result;
    try {
        result = _vpcService.createVpcPrivateGateway(getVpcId(), getStartIp(), getGateway(), getNetmask(), getEntityDomainId(), getNetworkId(), getIsSourceNat(), getAclId());
    } catch (final InsufficientCapacityException ex) {
        s_logger.info(ex.toString());
        throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage());
    } catch (final ConcurrentOperationException ex) {
        s_logger.warn("Exception: ", ex);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
    }
    if (result != null) {
        setEntityId(result.getId());
        setEntityUuid(result.getUuid());
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create private gateway");
    }
}
Also used : ServerApiException(com.cloud.api.ServerApiException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) PrivateGateway(com.cloud.legacymodel.network.vpc.PrivateGateway)

Example 7 with PrivateGateway

use of com.cloud.legacymodel.network.vpc.PrivateGateway in project cosmic by MissionCriticalCloud.

the class VpcNetworkHelperImpl method reallocateRouterNetworks.

@Override
public void reallocateRouterNetworks(final RouterDeploymentDefinition vpcRouterDeploymentDefinition, final VirtualRouter router, final VMTemplateVO template, final HypervisorType hType) throws ConcurrentOperationException, InsufficientCapacityException {
    final TreeSet<String> publicVlans = new TreeSet<>();
    if (vpcRouterDeploymentDefinition.needsPublicNic()) {
        publicVlans.add(vpcRouterDeploymentDefinition.getSourceNatIP().getVlanTag());
    } else {
        s_logger.debug("VPC " + vpcRouterDeploymentDefinition.getVpc().getName() + " does not need a public nic.");
    }
    // 1) allocate nic for control and source nat public ip
    final LinkedHashMap<Network, List<? extends NicProfile>> networks = configureDefaultNics(vpcRouterDeploymentDefinition);
    final Long vpcId = vpcRouterDeploymentDefinition.getVpc().getId();
    // 2) allocate nic for private gateways if needed
    final List<PrivateGateway> privateGateways = vpcMgr.getVpcPrivateGateways(vpcId);
    if (privateGateways != null && !privateGateways.isEmpty()) {
        for (final PrivateGateway privateGateway : privateGateways) {
            final NicProfile privateNic = nicProfileHelper.createPrivateNicProfileForGateway(privateGateway, router);
            final Network privateNetwork = _networkModel.getNetwork(privateGateway.getNetworkId());
            networks.put(privateNetwork, new ArrayList<>(Arrays.asList(privateNic)));
        }
    }
    // 3) allocate nic for guest gateway if needed
    final List<? extends Network> guestNetworks = vpcMgr.getVpcNetworks(vpcId);
    for (final Network guestNetwork : guestNetworks) {
        if (_networkModel.isPrivateGateway(guestNetwork.getId())) {
            continue;
        }
        if (guestNetwork.getState() == Network.State.Implemented || guestNetwork.getState() == Network.State.Setup) {
            final NicProfile guestNic = nicProfileHelper.createGuestNicProfileForVpcRouter(vpcRouterDeploymentDefinition, guestNetwork);
            networks.put(guestNetwork, new ArrayList<>(Arrays.asList(guestNic)));
        }
    }
    // 4) allocate nic for additional public network(s)
    final List<IPAddressVO> ips = _ipAddressDao.listByVpc(vpcId, false);
    final List<NicProfile> publicNics = new ArrayList<>();
    Network publicNetwork = null;
    for (final IPAddressVO ip : ips) {
        final PublicIp publicIp = PublicIp.createFromAddrAndVlan(ip, _vlanDao.findById(ip.getVlanId()));
        if ((ip.getState() == IpAddress.State.Allocated || ip.getState() == IpAddress.State.Allocating) && vpcMgr.isIpAllocatedToVpc(ip) && !publicVlans.contains(publicIp.getVlanTag())) {
            s_logger.debug("Allocating nic for router in vlan " + publicIp.getVlanTag());
            final NicProfile publicNic = new NicProfile();
            publicNic.setDefaultNic(false);
            publicNic.setIPv4Address(publicIp.getAddress().addr());
            publicNic.setIPv4Gateway(publicIp.getGateway());
            publicNic.setIPv4Netmask(publicIp.getNetmask());
            publicNic.setMacAddress(publicIp.getMacAddress());
            publicNic.setBroadcastType(BroadcastDomainType.Vlan);
            publicNic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(publicIp.getVlanTag()));
            publicNic.setIsolationUri(IsolationType.Vlan.toUri(publicIp.getVlanTag()));
            final NetworkOffering publicOffering = _networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemPublicNetwork).get(0);
            if (publicNetwork == null) {
                final List<? extends Network> publicNetworks = _networkMgr.setupNetwork(s_systemAccount, publicOffering, vpcRouterDeploymentDefinition.getPlan(), null, null, false);
                publicNetwork = publicNetworks.get(0);
            }
            publicNics.add(publicNic);
            publicVlans.add(publicIp.getVlanTag());
        }
    }
    if (publicNetwork != null) {
        if (networks.get(publicNetwork) != null) {
            final List<NicProfile> publicNicProfiles = (List<NicProfile>) networks.get(publicNetwork);
            publicNicProfiles.addAll(publicNics);
            networks.put(publicNetwork, publicNicProfiles);
        } else {
            networks.put(publicNetwork, publicNics);
        }
    }
    final ServiceOfferingVO routerOffering = _serviceOfferingDao.findById(vpcRouterDeploymentDefinition.getServiceOfferingId());
    _itMgr.allocate(router.getInstanceName(), template, routerOffering, networks, vpcRouterDeploymentDefinition.getPlan(), hType);
}
Also used : PublicIp(com.cloud.network.addr.PublicIp) NetworkOffering(com.cloud.offering.NetworkOffering) ArrayList(java.util.ArrayList) NicProfile(com.cloud.vm.NicProfile) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) PrivateGateway(com.cloud.legacymodel.network.vpc.PrivateGateway) TreeSet(java.util.TreeSet) Network(com.cloud.legacymodel.network.Network) ArrayList(java.util.ArrayList) List(java.util.List) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 8 with PrivateGateway

use of com.cloud.legacymodel.network.vpc.PrivateGateway in project cosmic by MissionCriticalCloud.

the class VpcManagerImpl method listPrivateGateway.

@Override
public Pair<List<PrivateGateway>, Integer> listPrivateGateway(final ListPrivateGatewaysCmd cmd) {
    final String ipAddress = cmd.getIpAddress();
    final String networkId = cmd.getNetworkId();
    final Long vpcId = cmd.getVpcId();
    final Long id = cmd.getId();
    Boolean isRecursive = cmd.isRecursive();
    final Boolean listAll = cmd.listAll();
    Long domainId = cmd.getDomainId();
    final String accountName = cmd.getAccountName();
    final Account caller = CallContext.current().getCallingAccount();
    final List<Long> permittedAccounts = new ArrayList<>();
    final String state = cmd.getState();
    final Long projectId = cmd.getProjectId();
    final Filter searchFilter = new Filter(VpcGatewayVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
    final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(domainId, isRecursive, null);
    _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, false);
    domainId = domainIdRecursiveListProject.first();
    isRecursive = domainIdRecursiveListProject.second();
    final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    final SearchBuilder<VpcGatewayVO> sb = _vpcGatewayDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    final SearchCriteria<VpcGatewayVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    if (id != null) {
        sc.addAnd("id", Op.EQ, id);
    }
    if (ipAddress != null) {
        sc.addAnd("ip4Address", Op.EQ, ipAddress);
    }
    if (state != null) {
        sc.addAnd("state", Op.EQ, state);
    }
    if (vpcId != null) {
        sc.addAnd("vpcId", Op.EQ, vpcId);
    }
    if (networkId != null) {
        sc.addAnd("networkId", Op.EQ, networkId);
    }
    final Pair<List<VpcGatewayVO>, Integer> vos = _vpcGatewayDao.searchAndCount(sc, searchFilter);
    final List<PrivateGateway> privateGtws = new ArrayList<>(vos.first().size());
    for (final VpcGateway vo : vos.first()) {
        privateGtws.add(getPrivateGatewayProfile(vo));
    }
    return new Pair<>(privateGtws, vos.second());
}
Also used : Account(com.cloud.legacymodel.user.Account) Ternary(com.cloud.legacymodel.utils.Ternary) ArrayList(java.util.ArrayList) PrivateGateway(com.cloud.legacymodel.network.vpc.PrivateGateway) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) Filter(com.cloud.utils.db.Filter) VpcGateway(com.cloud.legacymodel.network.vpc.VpcGateway) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) Pair(com.cloud.legacymodel.utils.Pair)

Example 9 with PrivateGateway

use of com.cloud.legacymodel.network.vpc.PrivateGateway in project cosmic by MissionCriticalCloud.

the class VpcManagerImpl method createVpcPrivateGateway.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PRIVATE_GATEWAY_CREATE, eventDescription = "creating VPC private gateway", create = true)
public PrivateGateway createVpcPrivateGateway(final long vpcId, final String ipAddress, final String gateway, final String netmask, final long gatewayDomainId, final Long networkId, final Boolean isSourceNat, final Long aclId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
    // Validate parameters
    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 on the VPC
    final CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    _accountMgr.checkAccess(caller, null, false, vpc);
    if (gateway != null || netmask != null) {
        throw new InvalidParameterValueException("Gateway/netmask fields are not supported anymore");
    }
    final Network privateNtwk = _ntwkDao.findById(networkId);
    if (privateNtwk == null) {
        throw new InvalidParameterValueException("The private network specified could not be found.");
    }
    if (privateNtwk.getDomainId() != vpc.getDomainId() && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new InvalidParameterValueException("VPC '" + vpc.getName() + "' does not have permission to operate on private network '" + privateNtwk.getName() + "' as they need to belong to the same domain.");
    }
    if (NetUtils.isNetworkAWithinNetworkB(privateNtwk.getCidr(), vpc.getCidr())) {
        throw new InvalidParameterValueException("CIDR of the private network to be connected " + privateNtwk.getCidr() + " should be outside of the VPC super CIDR " + vpc.getCidr());
    }
    if (!NetUtils.isIpWithtInCidrRange(ipAddress, privateNtwk.getCidr())) {
        throw new InvalidParameterValueException("The specified ip address for the private network " + ipAddress + " should be within the CIDR of the private network " + privateNtwk.getCidr());
    }
    final SortedSet<Long> availableIps = _ntwkModel.getAvailableIps(privateNtwk, ipAddress);
    if (availableIps == null || availableIps.isEmpty()) {
        throw new InvalidParameterValueException("The requested ip address " + ipAddress + " is not available in private network " + privateNtwk.getName());
    }
    final Long privateNetworkId = privateNtwk.getId();
    final List<PrivateGateway> privateGateways = getVpcPrivateGateways(vpcId);
    for (final PrivateGateway privateGateway : privateGateways) {
        if (privateNetworkId == privateGateway.getNetworkId()) {
            throw new InvalidParameterValueException("VPC with uuid " + vpc.getUuid() + " is already connected to network '" + privateNtwk.getName() + "'");
        }
    }
    final VpcGatewayVO gatewayVO;
    try {
        gatewayVO = Transaction.execute(new TransactionCallbackWithException<VpcGatewayVO, Exception>() {

            @Override
            public VpcGatewayVO doInTransaction(final TransactionStatus status) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
                // create the nic/ip as createPrivateNetwork doesn't do that work for us now
                s_logger.info("found and using existing network for vpc " + vpc + ": " + privateNtwk.getBroadcastUri());
                final DataCenterVO dc = _dcDao.lockRow(vpc.getZoneId(), true);
                // add entry to private_ip_address table
                PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkId(privateNtwk.getId(), ipAddress);
                if (privateIp != null) {
                    throw new InvalidParameterValueException("Private IP address " + ipAddress + " already used for private gateway in zone " + _entityMgr.findById(DataCenter.class, vpc.getZoneId()).getName());
                }
                final Long mac = dc.getMacAddress();
                final Long nextMac = mac + 1;
                dc.setMacAddress(nextMac);
                s_logger.info("creating private IP address for VPC (" + ipAddress + ", " + privateNtwk.getId() + ", " + nextMac + ", " + vpcId + ", " + isSourceNat + ")");
                privateIp = new PrivateIpVO(ipAddress, privateNtwk.getId(), nextMac, vpcId, isSourceNat);
                _privateIpDao.persist(privateIp);
                _dcDao.update(dc.getId(), dc);
                long networkAclId = NetworkACL.DEFAULT_DENY;
                if (aclId != null) {
                    final NetworkACLVO aclVO = _networkAclDao.findById(aclId);
                    if (aclVO == null) {
                        throw new InvalidParameterValueException("Invalid network acl id passed ");
                    }
                    if (aclVO.getVpcId() != vpcId && !(aclId == NetworkACL.DEFAULT_DENY || aclId == NetworkACL.DEFAULT_ALLOW)) {
                        throw new InvalidParameterValueException("Private gateway and network acl are not in the same vpc");
                    }
                    networkAclId = aclId;
                }
                // 2) create gateway entry
                final VpcGatewayVO gatewayVO = new VpcGatewayVO(ipAddress, VpcGateway.Type.Private, vpcId, privateNtwk.getDataCenterId(), privateNtwk.getId(), vpc.getAccountId(), vpc.getDomainId(), isSourceNat, networkAclId);
                _vpcGatewayDao.persist(gatewayVO);
                s_logger.debug("Created vpc gateway entry " + gatewayVO);
                return gatewayVO;
            }
        });
    } catch (final Exception e) {
        ExceptionUtil.rethrowRuntime(e);
        ExceptionUtil.rethrow(e, InsufficientCapacityException.class);
        ExceptionUtil.rethrow(e, ResourceAllocationException.class);
        throw new IllegalStateException(e);
    }
    CallContext.current().setEventDetails("Private Gateway Id: " + gatewayVO.getId());
    return getVpcPrivateGateway(gatewayVO.getId());
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.legacymodel.user.Account) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) Vpc(com.cloud.legacymodel.network.vpc.Vpc) TransactionStatus(com.cloud.utils.db.TransactionStatus) CallContext(com.cloud.context.CallContext) 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) PrivateGateway(com.cloud.legacymodel.network.vpc.PrivateGateway) DataCenter(com.cloud.legacymodel.dc.DataCenter) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PhysicalNetwork(com.cloud.network.PhysicalNetwork) Network(com.cloud.legacymodel.network.Network) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 10 with PrivateGateway

use of com.cloud.legacymodel.network.vpc.PrivateGateway in project cosmic by MissionCriticalCloud.

the class VpcManagerImpl method deleteVpcPrivateGateway.

@Override
@ActionEvent(eventType = EventTypes.EVENT_PRIVATE_GATEWAY_DELETE, eventDescription = "deleting private gateway")
@DB
public boolean deleteVpcPrivateGateway(final long gatewayId) throws ConcurrentOperationException, ResourceUnavailableException {
    final VpcGatewayVO gatewayVO = _vpcGatewayDao.acquireInLockTable(gatewayId);
    if (gatewayVO == null || gatewayVO.getType() != VpcGateway.Type.Private) {
        throw new ConcurrentOperationException("Unable to lock gateway " + gatewayId);
    }
    try {
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(final TransactionStatus status) {
                // don't allow to remove gateway when there are static routes pointing to an ipaddress in the private gateway CIDR.
                final List<? extends StaticRoute> routes = _staticRouteDao.listByVpcIdAndNotRevoked(gatewayVO.getVpcId());
                final NetworkVO network = _ntwkDao.findById(gatewayVO.getNetworkId());
                final List<String> wrongCidrs = new LinkedList<>();
                for (final StaticRoute route : routes) {
                    if (NetUtils.isIpWithtInCidrRange(route.getGwIpAddress(), network.getCidr())) {
                        wrongCidrs.add(route.getCidr());
                    }
                }
                if (!wrongCidrs.isEmpty()) {
                    throw new InvalidParameterValueException("Unable to delete Private Gateway. Please remove these static routes pointing to the private gateway CIDR" + " before attempting to delete the gateway: " + wrongCidrs);
                }
                gatewayVO.setState(VpcGateway.State.Deleting);
                _vpcGatewayDao.update(gatewayVO.getId(), gatewayVO);
                s_logger.debug("Marked gateway " + gatewayVO + " with state " + VpcGateway.State.Deleting);
            }
        });
        // Delete the gateway on the backend
        final List<Provider> providersToImplement = getVpcProviders(gatewayVO.getVpcId());
        final PrivateGateway gateway = getVpcPrivateGateway(gatewayId);
        for (final VpcProvider provider : getVpcElements()) {
            if (providersToImplement.contains(provider.getProvider())) {
                if (provider.deletePrivateGateway(gateway)) {
                    s_logger.debug("Private gateway " + gateway + " was applied succesfully on the backend");
                } else {
                    s_logger.warn("Private gateway " + gateway + " failed to apply on the backend");
                    gatewayVO.setState(VpcGateway.State.Ready);
                    _vpcGatewayDao.update(gatewayVO.getId(), gatewayVO);
                    s_logger.debug("Marked gateway " + gatewayVO + " with state " + VpcGateway.State.Ready);
                    return false;
                }
            }
        }
        return deletePrivateGatewayFromTheDB(gateway);
    } finally {
        _vpcGatewayDao.releaseFromLockTable(gatewayId);
    }
}
Also used : StaticRoute(com.cloud.legacymodel.network.vpc.StaticRoute) NetworkVO(com.cloud.network.dao.NetworkVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) VpcProvider(com.cloud.network.element.VpcProvider) Provider(com.cloud.legacymodel.network.Network.Provider) PrivateGateway(com.cloud.legacymodel.network.vpc.PrivateGateway) VpcProvider(com.cloud.network.element.VpcProvider) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

PrivateGateway (com.cloud.legacymodel.network.vpc.PrivateGateway)12 ArrayList (java.util.ArrayList)6 List (java.util.List)5 NetworkVO (com.cloud.network.dao.NetworkVO)4 ServerApiException (com.cloud.api.ServerApiException)3 ActionEvent (com.cloud.event.ActionEvent)3 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)3 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)3 Network (com.cloud.legacymodel.network.Network)3 Account (com.cloud.legacymodel.user.Account)3 IPAddressVO (com.cloud.network.dao.IPAddressVO)3 LinkedList (java.util.LinkedList)3 PrivateGatewayResponse (com.cloud.api.response.PrivateGatewayResponse)2 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)2 Provider (com.cloud.legacymodel.network.Network.Provider)2 Vpc (com.cloud.legacymodel.network.vpc.Vpc)2 VpcGateway (com.cloud.legacymodel.network.vpc.VpcGateway)2 VpcProvider (com.cloud.network.element.VpcProvider)2 DB (com.cloud.utils.db.DB)2 Filter (com.cloud.utils.db.Filter)2